首页 > 代码库 > java excel导出(POI)

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 = "http://www.mamicode.com/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;
    }

 

参考链接:

http://blog.csdn.net/renlei0109/article/details/36906409 http://bbs.csdn.net/topics/391888713?page=1
http://www.jb51.net/article/87574.htm
http://www.cnblogs.com/crazyapple/p/5489588.html
http://blog.csdn.net/houxuehan/article/details/50960259
http://blog.csdn.net/lp1791803611/article/details/52351333
http://yjck.iteye.com/blog/1609232
 

java excel导出(POI)