java excel导出(POI)

Posted dali_lyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java excel导出(POI)相关的知识,希望对你有一定的参考价值。

需要引入的jar包:

      <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>

1、前端

$(\'#exportBtn\').on(\'click\', function () {
    var hasChecked = $(\'input[name=clientOption]\').is(\':checked\');
    if (!hasChecked) {
        $.tip({text: \'请至少选择一个!\', status: \'confirm\'});return;
    }
    var values = [];
    $(\'input[name=clientOption]:checked\').each(function () {
        values.push($(this).val());
    })
    location.href = \'/admin/export?values=\' + values;
})

2、后端接收,并生成原始的List数据

  @RequestMapping(value = "export")
    public void exportClient(String[] values, HttpServletResponse response) {
        try {
            String title = "Title";
            Map<Integer, String> headerMap = new LinkedHashMap<>(3);
            headerMap.put(0, "Header0");
            headerMap.put(1, "Header1");
            headerMap.put(2, "Header2");
            List<List<String>> contentList = new ArrayList<>();
            for (int index = 0; index < values.length; index++) {
                List<String> cellList = new ArrayList<>();
                contentList.add(values[index]);
            }
            ExcelHelper.downloadExcel(response, title, headerMap, contentList);
        } catch (Exception e) {
            // todo
        }
    }

3、下载

  public static void downloadExcel(HttpServletResponse response, String title, Map<Integer, String> headerMap, List<List<String>> contentList) {
        try {
            // 内容写入Excel
            XSSFWorkbook workbook = ExcelHelper.writeToExcel(title, headerMap, contentList);
            // workbook写入到输出流中
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            // 设置response参数,打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((title + DateUtils.toDateText(new Date(), DateUtils.NUMBER_TIME_FORMAT) + ".xlsx").getBytes(), CHARSET_ISO_8859_1));
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            // 关闭输入输出流
            bis.close();
            bos.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            // todo
        }
    }

4、List写入到Excel对象中

  public static XSSFWorkbook writeToExcel(String title, Map<Integer, String> headerMap, List<List<String>> contentList) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            XSSFSheet sheet = workbook.createSheet(title);
            // excel样式设置
            XSSFCellStyle titleStyle = workbook.createCellStyle();
            titleStyle.setAlignment(HorizontalAlignment.CENTER);
            Font titleFont = workbook.createFont();
            titleFont.setFontHeightInPoints((short) 12);
            titleFont.setFontName("Microsoft YaHei");
            titleFont.setBold(true);
            titleStyle.setFont(titleFont);

            // 写入标题
            XSSFRow row0 = sheet.createRow(0);
            XSSFCell row0cell0 = row0.createCell(0);
            row0cell0.setCellValue(title);
            row0cell0.setCellStyle(titleStyle);
            // excel合并单元格
            CellRangeAddress region = new CellRangeAddress(0, 0, 0, headerMap.size() - 1);
            sheet.addMergedRegion(region);

            //写入主体内容
            for (int rowIndex = 0; rowIndex < contentList.size(); rowIndex++) {
                XSSFRow rows = sheet.createRow(rowIndex + 2);
                List<String> rowList = contentList.get(rowIndex);
                for (int cellIndex = 0; cellIndex < rowList.size(); cellIndex++) {
                    rows.createCell(cellIndex).setCellValue(rowList.get(cellIndex));
                }
            }

            // 写入头部列
            XSSFRow row1 = sheet.createRow(1);
            for (int headerIndex = 0; headerIndex < headerMap.size(); headerIndex++) {
                row1.createCell(headerIndex).setCellValue(headerMap.get(headerIndex));
          // sheet.autoSizeColumn(headerIndex, true);
                sheet.setColumnWidth(headerIndex, row1.getCell(headerIndex).toString().getBytes().length * 3 * 256);
            }
        } catch (Exception e) {
            // todo
        }
        return workbook;
    }

 

参考链接:

以上是关于java excel导出(POI)的主要内容,如果未能解决你的问题,请参考以下文章

java poi导出excel

java poi xwpf操作word生成一个表格怎么合并单元格,求大神指导!

Java poi导出Excel,小数点后面数据缺失

急!!!java用poi导出excel文件,打开导出的文件时报错“文件错误,数据可能丢失”

java 通过Apache poi导出excel代码demo实例

关于java poi导出excel弹出下载框无法弹出的问题