java实现Excel动态列导出的简单例子

可以通过该对象的set方法设置各个参数,headKey保存结果集中,数据对应的key值,ArrayList最佳,保证了导出列的顺序,同时限制了每个sheet页保存的最大数据行数为5W条,这些参数也可以放到属性中进行设置。

@Data
public class ExcelExportUtil {

    //表头
    private String title;
    //各个列的表头
    private List<String> headList;
    //各个列的元素key值
    private List<String> headKey;
    // 各个列的宽度
    private List<Integer> headWidth;
    //需要填充的数据信息
    private List<HashMap> data;
    //字体大小
    private int fontSize = 14;
    //行高
    private int rowHeight = 30;
    //列宽
    private int columWidth = 200;
    //工作表
    private String sheetName = "sheet";
    // 文件名
    private String fileName;

    HSSFWorkbook wb;

    HSSFSheet sheet;

    HSSFCellStyle headCellStyle;

    HttpServletResponse response;

    public ExcelExportUtil exportExport(HttpServletResponse response) throws IOException {
        this.response = response;
        wb = new HSSFWorkbook();
        int size = data.size();
        int count = (size - 1) / 50000 + 1;
        for (int i = 0; i < count; i++) {
            sheet = wb.createSheet(sheetName + (i + 1));
            exportExport(sheet,
                    data.subList(i * 50000, ((i + 1) * 50000 > size ? size : 50000 * (i + 1))));
        }
        return this;
    }

    private void exportExport(HSSFSheet sheet, List<HashMap> data) throws IOException{

        //检查参数配置信息
        checkConfig();
        HSSFCellStyle cellStyle = wb.createCellStyle();
        HSSFDataFormat format = wb.createDataFormat();
        //这样才能真正的控制单元格格式,@就是指文本型
        cellStyle.setDataFormat(format.getFormat("@"));

        HSSFRow headRow = sheet.createRow(0);
        //设置列头元素
        for (int i = 0; i < headList.size(); i++) {
            Integer width = 15;
            if (headWidth != null && headWidth.size() >= headList.size()){
                width = headWidth.get(i);
            }
            sheet.setColumnWidth(i, 256 * width + 184);
            HSSFCell cellHead = headRow.createCell(i);
            cellHead.setCellValue(headList.get(i));
            cellHead.setCellStyle(headCellStyle);
        }

        //开始写入实体数据信息
        int a = 1;
        for (int i = 0; i < data.size(); i++) {
            HSSFRow row = sheet.createRow(a);
            HashMap map = data.get(i);
            HSSFCell cell;
            for (int j = 0; j < headKey.size(); j++) {
                cell = row.createCell(j);
                Object valueObject = map.get(headKey.get(j));
                if (valueObject == null) {
                    valueObject = "";
                }
                if (valueObject instanceof Integer) {
                    //取出的数据是Integer
                    cell.setCellValue(((Integer) (valueObject)).floatValue());
                } else if (valueObject instanceof BigDecimal) {
                    //取出的数据是BigDecimal
                    cell.setCellValue(((BigDecimal) (valueObject)).floatValue());
                } else {
                    //取出的数据是字符串直接赋值
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(Strings.isNullOrEmpty(String.valueOf(valueObject)) ? "" : String.valueOf(valueObject));
                }
            }
            a++;
        }
    }

    public void flushExplorer() throws Exception{
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "utf-8"));
        wb.write(response.getOutputStream());
    }

    /**
     * 检查数据配置问题
     *
     * @throws IOException 抛出数据异常类
     */
    protected void checkConfig() throws IOException {
        if (headKey == null) {
            throw new IOException("表头不能为空");
        }

        if (headWidth != null && headWidth.size() < headKey.size()){
            throw new IOException("设置宽度的列数必须超过表头列数");
        }

        if (fontSize < 0 || rowHeight < 0 || columWidth < 0) {
            throw new IOException("字体、宽度或者高度不能为负值");
        }

        if (Strings.isNullOrEmpty(sheetName)) {
            throw new IOException("工作表表名不能为NULL");
        }
        createDefaultHeadStyle();
    }

    public void createDefaultHeadStyle() {
        //创建表头样式
        headCellStyle= wb.createCellStyle();
        //居中
        headCellStyle.setAlignment(HorizontalAlignment.LEFT);
        //背景色
        headCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headCellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.PALE_BLUE.getIndex());

        //字体
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short)12);
        font.setBold(true);         //字体增粗
        headCellStyle.setFont(font);

        headCellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
        headCellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        headCellStyle.setBorderTop(BorderStyle.THIN);// 上边框
        headCellStyle.setBorderRight(BorderStyle.THIN);// 右边框
    }
}

简单的调用例子:

		ExcelExportUtil excelExportUtil = new ExcelExportUtil();
		// 表头固定列
        List<String> headList = new ArrayList<>();
        headList.add("省");
        if (param.getCity() != 0){
            headList.add("市");
        }

        // 表头固定key
        List<String> headKey = new ArrayList<>();
        headKey.add("province");
        if (param.getCity() != 0){
            headKey.add("city");
        }

        for (HashMap dateInfo : date){
            for (String key : param.getNeedType()){
                headList.add(dateInfo.get("day") + "日" + ConstantUtils.NEED_MAP.get(key));
                headKey.add(dateInfo.get("day") + "_" + key);
            }
        }

        excelExportUtil.setHeadList(headList);
        excelExportUtil.setHeadKey(headKey);
        excelExportUtil.setData(list);
        excelExportUtil.setFileName("XXX日账");
        excelExportUtil.exportExport(response).flushExplorer();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章