POI 之Excel導出

一、POI介紹

Java POI有很多組件組成,其中有用於操作Excel格式文件的HSSF和用於操作Word的HWPF,其中常用的的包有:

     

 

二、xml引入依賴

<!--讀取excel文件-->
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
</dependency>
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
</dependency>

三、使用Excel導出實例

    導出需要提供要導出的數據,和定義Excel的格式(sheel名,表頭,表格數據,寬度,及一些樣式等)

   controller 層獲取輸出流,設置文件類型,頭信息,文件名等

@PostMapping("bookExcel")
    @ApiOperation("武俠小說列表導出")
    public void getBookExcel(
            HttpServletResponse response,String bookIds
    ) {
        //從response中獲取輸出流
        try (OutputStream outputStream = response.getOutputStream()) {
            List<Book> bookList =bookService .selectAllExcel(bookIds);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("武俠小說彙總導出.xlsx", "UTF-8"));
            boolean success = excelExportService.bookExcel(outputStream, bookList);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

定義:Excel的表頭,填充每個單元格數據,列寬度,sheel名

public boolean bookExcel(OutputStream outputStream, List<Book> bookList){
        List<String[]> content = new ArrayList<>();
        for (Book book : bookList) {
            String[] str=new String[7];
            str[0] = String.valueOf(book.getBookId());
            str[1] = String.valueOf(isNull(book.getBookname()));
            str[2] = String.valueOf(isNull(book.getAuthorname()));
            str[3] = String.valueOf(isNull(book.getMainperson()));
            str[4] = String.valueOf(isNull(book.getDepartment()));
            str[5] = String.valueOf(isNull(book.getEsoterica()));
            str[6] = String.valueOf(isNull(book.getCreatetime()));
            content.add(str);
        }
        int[] widths = {3000,6000,4000,8000,8000,8000,4000};
        List<String> title = new ArrayList<>();
        title.add("編號ID");
        title.add("書名");
        title.add("作者");
        title.add("主要人物");
        title.add("主要門派");
        title.add("出現武功高");
        title.add("出版日期");
        Workbook sxssfWorkbook=excelExportUtils.export(title,"書籍導出", widths, content);
        // 數據寫入
        try {
            sxssfWorkbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

通用的Excel導出方法:

public SXSSFWorkbook export(List<String> title, String name, int[] widths, List<String[]> content) {
        SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
        CellStyle titleStyle = titleStyle(sxssfWorkbook);
        CellStyle tableStyle = tableStyle(sxssfWorkbook);
        //單元名:
        SXSSFSheet sheet = sxssfWorkbook.createSheet(name);
        //每一列的寬度
        for (int i = 0; i < widths.length; i++) {
            sheet.setColumnWidth(i, widths[i]);
        }
        //設置標題
        SXSSFRow row =sheet.createRow(0);
        Cell cell = null;
        for (int i = 0; i < title.size(); i++) {
            cell = row.createCell(i);
            cell.setCellStyle(titleStyle);
            cell.setCellValue(title.get(i));
        }
        //設置內容
        if (content != null) {
            int num = 1;
            for (String[] contents : content) {
                row = sheet.createRow(num++);
                for (int i = 0; i < contents.length; i++) {
                    cell = row.createCell(i);
                    cell.setCellStyle(tableStyle);
                    cell.setCellValue(contents[i]);
                }
            }
        }
        return sxssfWorkbook;
    }

設置表格內容樣式:

public CellStyle titleStyle(SXSSFWorkbook workbook) {
       CellStyle titleStyle = workbook.createCellStyle();
       //設置字體
       Font font =workbook.createFont();
       font.setFontName("宋體");//設置字體
       font.setBold(true);//字體加粗
       font.setItalic(false);//字體是否傾斜
       font.setFontHeightInPoints((short)22);//設置字體大小
       font.setColor(IndexedColors.BLACK.index);//設置字體顏色
       titleStyle.setFont(font);
       //設置顏色:
                    //設置前景顏色
       titleStyle.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.index);
                    //設置顏色填充規則
       titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
       //設置對齊方式:
       titleStyle.setAlignment(HorizontalAlignment.CENTER);
       titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
       //設置邊框樣式:
       titleStyle.setBorderTop(BorderStyle.THIN);
       titleStyle.setBorderBottom(BorderStyle.THIN);
       titleStyle.setBorderLeft(BorderStyle.THIN);
       titleStyle.setBorderLeft(BorderStyle.THIN);
       //設置邊框顏色:
       titleStyle.setBottomBorderColor(IndexedColors.BLACK.index);
       titleStyle.setTopBorderColor(IndexedColors.BLACK.index);
       titleStyle.setLeftBorderColor(IndexedColors.BLACK.index);
       titleStyle.setRightBorderColor(IndexedColors.BLACK.index);
       return titleStyle;
   }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章