spring boot 使用POI導出數據到Excel表格

  在spring boot 的項目常常碰到將數據導出到Excel表格的需求,而POI技術則對於java操做Excel表格提供了API,POI中對於多種類型的文檔都提供了操做的接口,可是其對於Excel表格的操做無疑是最強大的。css

  1.POI簡介

    Apache POI 是用 Java 編寫的免費開源的跨平臺的 Java API,Apache POI 提供 API 給 Java 程式對 Microsoft Office(Excel、WORD、PowerPoint、Visio 等,主要實現用於 Excel)格式檔案讀和寫的功能,POI 爲 「 Poor Obfuscation Implementation 」 的首字母縮寫,意爲簡潔版的模糊實現。java

   POI結構:spring

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[]>。apache

  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地址。restful

相關文章
相關標籤/搜索