Project in spring boot often encounter export data to Excel spreadsheet needs, and POI for java technology is operating Excel spreadsheet provides the API, POI in for many types of documents provide interface operation, but for its Excel spreadsheet the operation is undoubtedly the most powerful.
1.POI Profile
Apache POI is written in Java free and open source cross-platform Java API, Apache POI API to provide Java programs on Microsoft Office (Excel, WORD, PowerPoint, Visio, etc., the main achievement for Excel) format file read and write functions, POI is the first letter of "Poor Obfuscation Implementation" acronym, meaning simple version of the fuzzy implementation.
POI structure:
HSSF - provide read and write Microsoft Excel XLS file format functions. XSSF - provide functions to read and write Microsoft Excel OOXML XLSX format files. HWPF - provide functions to read and write Microsoft Word DOC97 format files. XWPF - provide read and write Microsoft Word file format functions DOC2003. HSLF - provide read and write Microsoft PowerPoint file format functions. HDGF - provides reading functionality of Microsoft Visio file format. HPBF - provides reading functionality of Microsoft Publisher file format. HSMF - provide read Microsoft Outlook file format functions.
Because using the POI operation of Excel, so tell us about HSSF in common class:
Class Explanation
HSSFWorkbook Excel document object
HSSFSheet Excel form
HSSFRow Excel row
grid unit HSSFCell Excel's
HSSFFont Excel font
date format HSSFDataFormat grid unit
headers HSSFHeader Excel documents Sheet of
HSSFFooter Excel documents Sheet footer
HSSFCellStyle grid cell style
HSSFDateUtil date
HSSFPrintSetup print
HSSFErrorConstants error information table
2. Import dependence POI in the project
<!-- 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 layer
@GetMapping ( "/ Export" ) public ResponseEntity < byte []> exportEmp () { List List = database query to all data to be exported ; return EmpUtils.exportEmp (the employeeList); }
First, from the database query to the specific data to be exported to Excel, controller layer, the return value ResponseEntity < byte []>.
Construction of Excel spreadsheet 4.Java use of poi
public class EmpUtils { public static ResponseEntity < byte []> exportEmp (List <the Employee> the employeeList) { // 1. Create an excel document HSSFWorkbook HSSFWorkbook = new new HSSFWorkbook (); // 2. Create document summary hssfWorkbook.createInformationProperties (); // 3. obtain and configure document summary information DocumentSummaryInformation DOCINFO = hssfWorkbook.getDocumentSummaryInformation (); // document category docInfo.setCategory ( "XXX information" ); // document administrator docInfo.setManager ( "Hope" ); // document belongs Company docInfo.setCompany ( "xxxx" ); // Issue docInfo.setApplicationVersion (1 ); // 4. get document summary information SummaryInformation SummaryInformation = hssfWorkbook.getSummaryInformation (); // document title summaryInformation.setAuthor ( "hopec" ); // document creation time summaryInformation.setCreateDateTime ( new new a Date ()); // document notes summaryInformation.setComments ( "documentation Notes" ); // 5. create style // create a header row style HeaderStyle = HSSFCellStyle hssfWorkbook.createCellStyle (); // set the style pattern color yellow // headerStyle.setFillForegroundColor (IndexedColors.GREEN.index); // set the color pattern // headerStyle.setFillBackgroundColor (IndexedColors.RED.index); // set the background color pattern headerStyle.setFillForegroundColor (IndexedColors.YELLOW.index); // set hatch pattern headerStyle.setFillPattern (FillPatternType.SOLID_FOREGROUND); // set the date associated style HSSFCellStyle dateCellStyle = hssfWorkbook.createCellStyle (); / / where m / d / yy yyyy-MM-dd equivalent 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("User ID" ); HSSFCell C3 = r0.createCell (. 3 ;) (headerStyle) c3.setCellStyle; c3.setCellValue ( "sex" ); HSSFCell C4 = r0.createCell (. 4 ;) (headerStyle) c4.setCellStyle; C4 .setCellValue ( "date of birth" ); HSSFCell c5 = r0.createCell (5 ); c5.setCellStyle (headerStyle); c5.setCellValue ( "ID number" ); HSSFCell c6 = r0.createCell (6 ); c6.setCellStyle (headerStyle); c6.setCellValue ( "marital status" ); 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 new ByteArrayOutputStream (); HttpHeaders headers = new new HttpHeaders (); the try { // the data table several Chinese words transcoding prevent the distortion deriving 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); } }
The page calls
exportEmp () { the this $ Confirm The ( 'This export employee data, whether to continue?', 'tips'. , { confirmButtonText: 'OK' , cancelButtonText: 'Cancel' , of the type: 'warning' }). the then (( ) => { the window.open ( '/ Employee / Basic / export', '_ parent' ) .}) the catch (() => { the this . Message $ ({ type: 'info' , Message: 'canceled exported' }); }); },
Where / employee / basic / export restfulAPI address for the background of the interface.