POI 之Excel导出

一、POI介绍

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

     

 

二、xml引入依赖



            org.apache.poi
            poi
            3.17


            org.apache.poi
            poi-ooxml
            3.17

三、使用Excel导出实例

    导出需要提供要导出的数据,和定义Excel的格式(sheel名,表头,表格数据,宽度,及一些样式等)

   controller 层获取输出流,设置文件类型,头信息,文件名等

@PostMapping("bookExcel")
    @ApiOperation("武侠小说列表导出")
    public void getBookExcel(
            HttpServletResponse response,String bookIds
    ) {
        //从response中获取输出流
        try (OutputStream outputStream = response.getOutputStream()) {
            List 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 bookList){
        List 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 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 title, String name, int[] widths, List 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;
   }

 

你可能感兴趣的:(java基础)