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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章