HSSFWorkbook生成Excel文件并导出

利用HSSFWorkbook生成Excel文件的代码网上有很多例子,此处是我自己项目中用到,稍加修改的demo,由于生成Excel文件中记录数行数超过6万多时会报错,本例中对数据量多的情况做了保护,超过5万条,再生成新的sheet,具体代码如下:

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;




    public ActionResult derivedDataToExcel(@JsonParam("filterMap") Map<String, Object> map, ErrorContext context) {


        FileOutputStream fos = null;
        FileInputStream in = null;
        OutputStream out = null;


        try {
            // 动态列获取
            String colNames = "";
            colNames = (String) map.get("colNames");
            // 处理列名字符串
            List<String> headColumnName = new ArrayList<String>();
            headColumnName = Arrays.asList(colNames.split(","));
            // 若一个列都不需要,直接返回
            if (CollectionUtils.isEmpty(headColumnName)) {
                return new ActionResult(false, I18CommonConstants.NO_DATA_ERROR);
            }
            List<HashMap> mapList = lassenLegalCaseBo.queryMyLegalCaseForMaintainer(map, null);
            // 写数据到Excel文件
            HSSFWorkbook workbook = exportExcel(headColumnName, mapList, 50000);
            String fileName = DateUtil.getTodayDateTime().replaceAll(" ", "").replaceAll(":", "").replaceAll("-", "")
                              + "_" + "data_result.xls";


            String dicPath = new File(".").getCanonicalPath();
            String srcPath = dicPath + Constants.EXCEL_DOWNLOAD_PATH + fileName;
            File newPath = new File(dicPath + Constants.EXCEL_DOWNLOAD_PATH);
            newPath.mkdirs();


            // 删除临时文件
            boolean success = fileDelete(newPath);
            if (success) {
                newPath.mkdirs();


                File file = new File(srcPath);
                fos = new FileOutputStream(file);
                workbook.write(fos);// 写文件
                // 设置响应头,控制浏览器下载该文件
                response.setHeader("content-disposition", "attachment;filename=" + fileName);
                // 读取要下载的文件,保存到文件输入流
                in = new FileInputStream(srcPath);
                // 创建输出流
                out = response.getOutputStream();
                // 创建缓冲区
                byte buffer[] = new byte[1024];
                int len = 0;
                // 循环将输入流中的内容读取到缓冲区当中
                while ((len = in.read(buffer)) > 0) {
                    // 输出缓冲区的内容到浏览器,实现文件下载
                    out.write(buffer, 0, len);
                }
            }
        } catch (Exception e) {
            logger.error("LassenMaintenanceRpc derivedDataToExcel error:", e);
            bizExceptions.handle(context, e);
        } finally {
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
        return new ActionResult(true, I18CommonConstants.SUCCESS);
    }


    /**
     * 导出数据为Excel
     *
     * @param headColumnName
     * @param headColumnWidth
     * @param listMap
     * @param rowSize 每页的记录数
     * @return
     */
    @SuppressWarnings({ "rawtypes" })
    private HSSFWorkbook exportExcel(List<String> headColumnName, List<HashMap> mapList, int rowSize) {


        int pages = 1;
        // 写数据到Excel文件
        HSSFWorkbook workBook = new HSSFWorkbook();// 创建excel文件对象
        // 设置表头字体
        Font headfont = workBook.createFont();
        headfont.setFontName("黑体");
        headfont.setFontHeightInPoints((short) 9);// 字体大小
        headfont.setBoldweight(Font.BOLDWEIGHT_BOLD);// 加粗


        CellStyle headStyle = workBook.createCellStyle(); // 表头第一列的样式
        headStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index); // 前景色设置
        headStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); // 填充模式 设置
        headStyle.setFont(headfont);
        headStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
        headStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
        headStyle.setWrapText(true);
        headStyle.setBorderRight(CellStyle.BORDER_THIN);
        headStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        headStyle.setBorderTop(CellStyle.BORDER_THIN);
        headStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        // 表格正文样式,背景色,边框
        CellStyle style = workBook.createCellStyle();
        style.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index); // 前景色设置
        style.setFillPattern(CellStyle.SOLID_FOREGROUND); // 填充模式 设置
        style.setBorderBottom(CellStyle.BORDER_THIN); // 设置单元格的边框为粗体
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 设置单元格的边框颜色
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());


        List<HashMap> listNew = new ArrayList<HashMap>();
        Row row;
        Cell cell;
        while (mapList.size() > 0) {
            listNew = mapList.subList(0, mapList.size() < rowSize ? mapList.size() : rowSize);
            HSSFSheet sheet = null;
            sheet = workBook.getSheet("DataResult" + pages);


            if (sheet == null) {
                sheet = workBook.createSheet("DataResult" + pages);
            } else {
                sheet = workBook.createSheet("DataResult" + (++pages));
            }
            row = sheet.createRow(0);// 第一行,标题
            // 设置第一行标题
            for (int i = 0; i < headColumnName.size(); i++) {
                cell = row.createCell(i);
                cell.setCellValue(headColumnName.get(i));
                cell.setCellStyle(headStyle);
            }
            // 设置列宽
            for (int i = 0; i < headColumnName.size(); i++) {
                sheet.setColumnWidth(i, 18 * 256);
            }
            // 设置正文内容
            for (int i = 0, len = listNew.size(); i < len; i++) {// 循环创建数据行
                row = sheet.createRow(i + 1);
                for (int j = 0; j < headColumnName.size(); j++) {
                    cell = row.createCell(j);
                    // 可优化改进 TODO
                    String cellValue = (String) listNew.get(i).get(headColumnName.get(j));
                    if ("&nbsp;".equals(cellValue)) {
                        cellValue = "";
                    }
                    cell.setCellValue(cellValue);
                    cell.setCellStyle(style);
                }
            }


            if (mapList.size() > rowSize) {
                mapList = mapList.subList(rowSize, mapList.size());
            } else {
                mapList.clear();
            }
        }
        return workBook;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值