码迷,mamicode.com
首页 > 编程语言 > 详细

java excel导出(POI)

时间:2017-08-09 10:06:17      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:tip   har   tostring   rtc   cells   ati   tcl   3.1   export   

需要引入的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)

标签:tip   har   tostring   rtc   cells   ati   tcl   3.1   export   

原文地址:http://www.cnblogs.com/dali-lyc/p/7323357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!