spring boot 使用POI匯出資料到Excel表格
阿新 • • 發佈:2019-12-26
在spring boot 的專案經常碰到將資料匯出到Excel表格的需求,而POI技術則對於java操作Excel表格提供了API,POI中對於多種型別的文件都提供了操作的介面,但是其對於Excel表格的操作無疑是最強大的。
1.POI簡介
Apache POI 是用 Java 編寫的免費開源的跨平臺的 Java API,Apache POI 提供 API 給 Java 程式對 Microsoft Office(Excel、WORD、PowerPoint、Visio 等,主要實現用於 Excel)格式檔案讀和寫的功能,POI 為 “ Poor Obfuscation Implementation ” 的首字母縮寫,意為簡潔版的模糊實現。
POI結構:
HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能。 XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。 HWPF - 提供讀寫Microsoft Word DOC97格式檔案的功能。 XWPF - 提供讀寫Microsoft Word DOC2003格式檔案的功能。 HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。 HDGF - 提供讀Microsoft Visio格式檔案的功能。 HPBF - 提供讀Microsoft Publisher格式檔案的功能。 HSMF - 提供讀Microsoft Outlook格式檔案的功能。
因為使用的是POI對Excel的操作,所以先介紹一下HSSF中的常用類:
類名 說明 HSSFWorkbook Excel的文件物件 HSSFSheet Excel的表單 HSSFRow Excel的行 HSSFCell Excel的格子單元 HSSFFont Excel字型 HSSFDataFormat 格子單元的日期格式 HSSFHeader Excel文件Sheet的頁首 HSSFFooter Excel文件Sheet的頁尾 HSSFCellStyle 格子單元樣式 HSSFDateUtil 日期 HSSFPrintSetup 列印 HSSFErrorConstants 錯誤資訊表
2.在專案中匯入POI的依賴
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency>
3.controller層
@GetMapping("/export") public ResponseEntity<byte[]> exportEmp(){ List list = 資料庫查詢到所有要匯出的資料; return EmpUtils.exportEmp(employeeList); }
首先從資料庫查詢到具體的要匯出到Excel的資料,controller層的返回值為ResponseEntity<byte[]>。
4.Java使用poi的構建Excel表格
public class EmpUtils { public static ResponseEntity<byte[]> exportEmp(List<Employee> employeeList) { //1.建立一個excel文件 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); //2.建立文件摘要 hssfWorkbook.createInformationProperties(); //3.獲取並配置文件摘要資訊 DocumentSummaryInformation docInfo = hssfWorkbook.getDocumentSummaryInformation(); //文件類別 docInfo.setCategory("XXX資訊"); //文件管理員 docInfo.setManager("hope"); //文件所屬公司 docInfo.setCompany("xxxx"); //文件版本 docInfo.setApplicationVersion(1); //4.獲取文件摘要資訊 SummaryInformation summaryInformation = hssfWorkbook.getSummaryInformation(); //文件標題 summaryInformation.setAuthor("hopec"); //文件建立時間 summaryInformation.setCreateDateTime(new Date()); //文件備註 summaryInformation.setComments("文件備註"); //5.建立樣式 //建立標題行的樣式 HSSFCellStyle headerStyle = hssfWorkbook.createCellStyle(); //設定該樣式的圖案顏色為黃色 // headerStyle.setFillForegroundColor(IndexedColors.GREEN.index);//設定圖案顏色 // headerStyle.setFillBackgroundColor(IndexedColors.RED.index);//設定圖案背景色 headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index); //設定圖案填充的樣式 headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); //設定日期相關的樣式 HSSFCellStyle dateCellStyle = hssfWorkbook.createCellStyle(); //這裡的m/d/yy 相當於yyyy-MM-dd dateCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); HSSFSheet sheet = hssfWorkbook.createSheet("xxx資訊表"); //設定每一列的寬度 sheet.setColumnWidth(0,5*256); sheet.setColumnWidth(1,12*256); sheet.setColumnWidth(2,10*256); sheet.setColumnWidth(3,5*256); sheet.setColumnWidth(4,16*256); sheet.setColumnWidth(5,20*256); sheet.setColumnWidth(6,10*256); sheet.setColumnWidth(7,10*256); sheet.setColumnWidth(8,18*256); sheet.setColumnWidth(9,12*256); //6.建立標題行 HSSFRow r0 = sheet.createRow(0); HSSFCell c0 = r0.createCell(0); c0.setCellValue("編號"); c0.setCellStyle(headerStyle); HSSFCell c1 = r0.createCell(1); c1.setCellStyle(headerStyle); c1.setCellValue("姓名"); HSSFCell c2 = r0.createCell(2); c2.setCellStyle(headerStyle); c2.setCellValue("工號"); HSSFCell c3 = r0.createCell(3); c3.setCellStyle(headerStyle); c3.setCellValue("性別"); HSSFCell c4 = r0.createCell(4); c4.setCellStyle(headerStyle); c4.setCellValue("出生日期"); HSSFCell c5 = r0.createCell(5); c5.setCellStyle(headerStyle); c5.setCellValue("身份證號碼"); HSSFCell c6 = r0.createCell(6); c6.setCellStyle(headerStyle); c6.setCellValue("婚姻狀況"); HSSFCell c7 = r0.createCell(7); c7.setCellStyle(headerStyle); c7.setCellValue("民族"); HSSFCell c8 = r0.createCell(8); c8.setCellStyle(headerStyle); c8.setCellValue("籍貫"); HSSFCell c9 = r0.createCell(9); c9.setCellStyle(headerStyle); c9.setCellValue("政治面貌"); HSSFCell c10 = r0.createCell(10); for (int i = 0; i < employeeList.size(); i++) { Employee employee= employeeList.get(i); HSSFRow row = sheet.createRow(i+1); row.createCell(0).setCellValue(employee.getId()); row.createCell(1).setCellValue(employee.getName()); row.createCell(2).setCellValue(employee.getWorkID()); row.createCell(3).setCellValue(employee.getGender()); HSSFCell cell4 = row.createCell(4); //單獨設定日期的樣式 cell4.setCellStyle(dateCellStyle); cell4.setCellValue(employee.getBirthday()); row.createCell(5).setCellValue(employee.getIdCard()); row.createCell(6).setCellValue(employee.getWedlock()); row.createCell(7).setCellValue(employee.getNation().getName()); row.createCell(8).setCellValue(employee.getNativePlace()); row.createCell(9).setCellValue(employee.getPoliticsstatus().getName()); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); HttpHeaders headers = new HttpHeaders(); try { //將資料表這幾個中文的字轉碼 防止匯出後亂碼 headers.setContentDispositionFormData("attachment", new String("資料表.xls".getBytes("UTF-8"),"ISO-8859-1")); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); hssfWorkbook.write(stream); } catch (IOException e) { e.printStackTrace(); } return new ResponseEntity<byte[]>(stream.toByteArray(),headers, HttpStatus.CREATED); } }
5.頁面呼叫
exportEmp(){ this.$confirm('此操作將匯出員工資料, 是否繼續?', '提示', { confirmButtonText: '確定', cancelButtonText: '取消', type: 'warning' }).then(() => { window.open('/employee/basic/export','_parent') }).catch(() => { this.$message({ type: 'info', message: '已取消匯出' }); }); },
其中/employee/basic/export為後臺介面的restfulAPI地址