POI匯出Excel簡單示例
阿新 • • 發佈:2018-11-12
簡單示例,poi操作Excel實現中文列寬自適應。
maven專案,在pom.xml檔案中引入poi的jar包依賴。
非maven專案需要先下載poi相關jar包匯入。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
組裝資料介面。
package com.aliyun.xclouddesk.webapi.chart; import com.aliyun.xclouddesk.utils.ExcelUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.Getter; import lombok.Setter; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * 報表匯出 * @author khWang * @date 2018/9/12 */ @Api(value = "ChartTypeLatTotalController", description = "chart_type_lat報表匯出") @Controller @RequestMapping("/v1/tenants") public class ChartDownloadController { @Autowired private HttpServletResponse response; @RequestMapping(value = "/{tenantId}/charts/download/{channelCode}/", method = RequestMethod.GET) @ResponseBody @ApiOperation(value = "測試", produces = "application/octet-stream") public void chartDownloadServices() { //獲取資料 List<PageData> list = getData(); //excel標題 String[] title = {"名稱", "性別", "年齡", "學校", "班級"}; //excel檔名 String fileName = "學生資訊表" + System.currentTimeMillis() + ".xls"; //sheet名 String sheetName = "學生資訊表"; String[][] content = new String[list.size()][]; for (int i = 0; i < list.size(); i++) { content[i] = new String[title.length]; PageData obj = list.get(i); content[i][0] = obj.getStuName(); content[i][1] = obj.getStuSex(); content[i][2] = String.valueOf(obj.getStuAge()); content[i][3] = obj.getStuSchoolName(); content[i][4] = obj.getStuClassName(); } //建立HSSFWorkbook HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content); //響應到客戶端 try { this.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 傳送響應流方法 * * @param response * @param fileName */ public void setResponseHeader(HttpServletResponse response, String fileName) { try { fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1"); response.setContentType("application/octet-stream;charset=ISO-8859-1"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.addHeader("Param", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); } } @Getter @Setter class PageData { String stuName; String stuSex; int stuAge; String stuSchoolName; String stuClassName; } public List<PageData> getData() { List<PageData> list = new ArrayList<PageData>(); PageData pageData; for (int i = 0; i < 10; i++) { pageData = new PageData(); if (i == 4) { pageData.setStuAge(999990 + i); pageData.setStuClassName("班級班級" + i); pageData.setStuName("姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名姓名" + i); pageData.setStuSchoolName("學校學校學校" + i); pageData.setStuSex("男"); } else { pageData.setStuAge(i); pageData.setStuClassName("班級" + i); pageData.setStuName("姓名" + i); pageData.setStuSchoolName("學校" + i); pageData.setStuSex("男"); } list.add(pageData); } return list; } }
POI操作Excel通用工具類
package com.aliyun.xclouddesk.utils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; /** * POI操作Excel工具類 * @author khWang * @date 2018/9/12 */ public class ExcelUtils { /** * Excel資料填充 * * @param sheetName sheet名稱 * @param title 標題 * @param values 內容 * @return */ public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values) { // 第一步,建立一個HSSFWorkbook,對應一個Excel檔案 HSSFWorkbook workbook = new HSSFWorkbook(); // 第二步,在workbook中新增一個sheet,對應Excel檔案中的sheet HSSFSheet sheet = workbook.createSheet(sheetName); // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制 HSSFRow row = sheet.createRow(0); // 第四步,建立單元格,並設定值表頭 設定表頭居中 HSSFCellStyle titleStyle = workbook.createCellStyle(); // 設定自動換行 titleStyle.setWrapText(true); // 建立一個居中格式 titleStyle.setAlignment(HorizontalAlignment.CENTER); titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); titleStyle.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); titleStyle.setBorderBottom(BorderStyle.THIN); titleStyle.setBorderLeft(BorderStyle.THIN); titleStyle.setBorderRight(BorderStyle.THIN); titleStyle.setBorderTop(BorderStyle.THIN); // 建立字型樣式 HSSFFont headerFont = (HSSFFont) workbook.createFont(); // 字型加粗 headerFont.setBold(true); // 為標題樣式設定字型樣式 titleStyle.setFont(headerFont); //宣告列物件 HSSFCell cell; //該陣列儲存每一列的最大寬度值 int[] widthMax = new int[title.length]; //建立標題 for (int i = 0; i < title.length; i++) { cell = row.createCell(i); cell.setCellValue(title[i]); cell.setCellStyle(titleStyle); int width = title[i].getBytes().length * 256 + 256; widthMax[i] = width; sheet.setColumnWidth(i, width); } HSSFCellStyle contentStyle = workbook.createCellStyle(); // 設定自動換行 contentStyle.setWrapText(true); // 建立一個居中格式 contentStyle.setAlignment(HorizontalAlignment.CENTER); contentStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 設定邊框 contentStyle.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex()); contentStyle.setBorderBottom(BorderStyle.THIN); contentStyle.setBorderLeft(BorderStyle.THIN); contentStyle.setBorderRight(BorderStyle.THIN); contentStyle.setBorderTop(BorderStyle.THIN); //建立內容 HSSFCell contentCell; for (int i = 0; i < values.length; i++) { row = sheet.createRow(i + 1); for (int j = 0; j < values[i].length; j++) { int width = values[i][j].getBytes().length * 256 + 256; if (width > widthMax[j]) { widthMax[j] = width; sheet.setColumnWidth(j, width); } contentCell = row.createCell(j); //將內容按順序賦給對應的列物件 contentCell.setCellValue(values[i][j]); contentCell.setCellStyle(contentStyle); } } return workbook; } }
預設字型的大小應該是10,每個字元佔用空間在Excel中是256個單位,為了使佈局看上去不那麼緊湊,每個單元格多讓出一個字元的空間。一個漢字佔用兩個字元,但實際視覺上,一個漢字所佔用的空間和兩個英文字元相比少那麼一點點,所以當漢字長度很長的時候,會感覺單元格空白空間比較多。