1. 程式人生 > >【工具類】Excel匯出那些事兒(三)

【工具類】Excel匯出那些事兒(三)

      匯出Excel又有了新的需求,之前都是直接匯出list<T>,現需要匯出List<map>,並且需要動態建立表頭。如下:

【工具類】

引用jxl包

 



public class ListMapExportExcelUtil {

    /**
     * 寫excel.
     *
     * @param fileName         檔名
     * @param sheetName        sheet名
     * @param mapKeyListString map的key,表頭們
     * @param dataListMap      資料
     */
    public static void writeExcel(HttpServletResponse response,String fileName,
                           String sheetName,
                               List<String> mapKeyListString, List<Map<String, Object>> dataListMap) throws EngineException {
        WritableWorkbook wwb = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            wwb = Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet(sheetName, 0);

            int size = mapKeyListString.size();
            insertHead(ws, mapKeyListString);

            int rownum = 1;
            if ((dataListMap != null) && (dataListMap.size() > 0)) {
                for (int i = 0; i < dataListMap.size(); i++) {
                    LogUtil.getAppLogger().info("當前行數為:{}",i);
                    Map map = (Map) dataListMap.get(i);
                    for (int j = 0; j < mapKeyListString.size(); j++) {
                        if(map.get(mapKeyListString.get(j)) != null ){
                            insertCell(ws, null, rownum, j, map.get(mapKeyListString.get(j)).toString());
                        }else{
                            insertCell(ws, null, rownum, j, " ");
                        }
                    }

                    rownum++;
                }

            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            response.setContentType("application/msexcel");
            response.addHeader("Content-disposition", "attachment;" +
                    "filename=" + fileName + "_" + sdf.format(new Date()
            ) + ".xls");
            wwb.write();
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            try {
                if (wwb != null)
                    wwb.close();
                if (os != null)
                    os.close();
            } catch (Exception e) {
                throw new Exception(e);
            }
        }
    }

    //單元格
    private static void insertCell(WritableSheet writableSheet, WritableCellFormat writableCellFormat, int row, int column, String name) throws RowsExceededException, WriteException {
        WritableCell cell = new Label(column, row, name);
        if (writableCellFormat != null) {
            cell.setCellFormat(writableCellFormat);
        }
        writableSheet.addCell(cell);
    }

    //表頭
    private static void insertHead(WritableSheet writableSheet, List<String> titleColumn) throws RowsExceededException, WriteException, EngineException {
        WritableFont writableFont = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD);
        WritableCellFormat writableCellFormat = new WritableCellFormat(writableFont);

        try {
            writableCellFormat.setAlignment(Alignment.CENTRE);
        } catch (WriteException e) {
            throw new EngineException(CodeEnum.PARAM_FORMAT_ERROR.getCode(),CodeEnum.PARAM_FORMAT_ERROR.getMessage(),e);
        }
        for (int i = 0; i < titleColumn.size(); i++) {
            WritableCell cell = new Label(i, 0, titleColumn.get(i));
            cell.setCellFormat(writableCellFormat);
            writableSheet.addCell(cell);
        }

    }
}