1、使用注解導出excel
2、使用模板導出excel
/** * @Description: * @param response * @param request * @param planTotalId * @param planTotalIdGroup * @param orgId * @author houChen * @date 2020/5/4 17:27 */ @RequestMapping(value="exportexcel") @ResponseBody public void exportExcelTest(HttpServletResponse response,HttpServletRequest request,Long planTotalId, Long planTotalIdGroup,Long orgId){ Workbook workbook = fmexpenseplantotalService.constructWorkbook1(planTotalId,planTotalIdGroup,orgId); downLoadExcel("資金支出申報表.xlsx", response, workbook); }
//將workbook 寫出到response流中 private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { e.getStackTrace(); } }
/**
* @Description: 使用 Easyiop 的模板方式導出 excel (注釋模板混用 ==》 合並單元格)
* @param planTotalId
* @param planTotalIdGroup
* @param orgId
* @author houChen
* @date 2020/4/30 15:43 注意:這是我自己構造的數據,你們要按照你們的實際需求來構造數據
*/
public Workbook constructWorkbook1(Long planTotalId, Long planTotalIdGroup, Long orgId) {
TemplateExportParams params = new TemplateExportParams("static/template/ExcelTemplate.xlsx");
Map<String, Object> map = new HashMap<String, Object>(); //構造模板需要的相關信息
// 查詢導出的excel的表頭和表尾信息
Map<String, Object> p = new HashMap<String, Object>();
p.put("planTotalId", planTotalId);
Map<String, Object> info = bSqlHelper.getMap("business.fm.FmExpensePlanTotal.getBaseInfo", p);
map.put("month",Objects.toString(info.get("month"),""));
map.put("orgName",Objects.toString(info.get("orgIdName"),""));
map.put("yearC",Objects.toString(info.get("yearC"),""));
map.put("monthC",Objects.toString(info.get("monthC"),""));
map.put("dayC",Objects.toString(info.get("dayC"),""));
map.put("createAccountText",Objects.toString(info.get("createAccountText"),""));
map.put("businessDeptName", "");
//獲取事業部名稱
String org = Objects.toString(info.get("orgId"), "");
if(!"".equals(org)){
Long belongDept = basOrgService.findByOrgId(Long.parseLong(org)).getBelongDept();
if(belongDept!=null){
map.put("businessDeptName",basDeptService.findByDeptId(belongDept).getDeptName());
}
}
// 匯總的審批意見
Map<String, Map<String, Object>> formAdvices = flowUtilService.queryWorkMemory("FmExpensePlanTotal", Long.parseLong(Objects.toString(info.get("processinstid"))));
map.put("deptOpinion", formAdvices.get("deptOpinion").get("accountName"));
map.put("leader", formAdvices.get("leader").get("accountName"));
List<ExcelEntity> result =new ArrayList<>();
//1、構造日常支出費用的List
// 獲取 事業部資金計划匯總下的所有資金計划 + 資金計划關聯的明細 (1、收支計划ID 2,收支計划名稱 3、收支計划數量)
Double totalMoneyForExpense =0d;//日常費用支出合計
Double totalMoneyForProject =0d;//項目建設支出總的合計
Long expenseEndRow = 0L; // 日常收支計划 第二列合並結束的行數
List<Map<String,Object>> statisticInfoByClassId = fmexpenseplandetailService.statisticByClassIdAndPlanTotalId(planTotalId);
for(Map<String,Object> m:statisticInfoByClassId){
String classId = Objects.toString(m.get("classId"), "");
Double applyMoneyByclassid= Double.parseDouble(Objects.toString(m.get("applyMoneyByclassid"), "0"));
totalMoneyForExpense += applyMoneyByclassid;
//每個收支項目明細的個數
String classNumStr = Objects.toString(m.get("classNum"), "0");
long classNum = Long.parseLong(classNumStr);
expenseEndRow+=(classNum+1);
// 根據planTotalId 和 classId 獲取資金收支計划的子表信息
if(!"".equals(classId)){
List<Map<String,Object>> detailList = fmexpenseplandetailService.findDetailListByPlanTotalId(planTotalId,Long.parseLong(classId));
for(Map<String,Object> detail:detailList){
ExcelEntity a =new ExcelEntity();
a.setTopClass("日常支出費用");
a.setSecClass(Objects.toString(m.get("className"),""));
a.setSystemName(Objects.toString(detail.get("systemName"),""));
a.setApplyMoney(Objects.toString(detail.get("applyMoney"),""));
a.setDeptName(Objects.toString(detail.get("deptName"),""));
a.setReceiveUnit("");
a.setBudgetBase("");
a.setRemark(Objects.toString(detail.get("remark"),""));
result.add(a);
}
//每個收支分類的合計
ExcelEntity heji =new ExcelEntity();
heji.setTopClass("日常支出費用");
heji.setSecClass(Objects.toString(m.get("className"),""));
heji.setSystemName("合計");
heji.setApplyMoney(applyMoneyByclassid.toString());
heji.setDeptName("");
heji.setReceiveUnit("");
heji.setBudgetBase("");
heji.setRemark("");
result.add(heji);
}
}
//日常收支費用的合計
ExcelEntity heji1 =new ExcelEntity();
heji1.setTopClass("日常支出費用");
heji1.setSecClass("合計");
heji1.setSystemName("合計");
heji1.setApplyMoney(totalMoneyForExpense.toString());
heji1.setDeptName("");
heji1.setReceiveUnit("");
heji1.setBudgetBase("");
heji1.setRemark("");
result.add(heji1);
// 集團 資金收支計划匯總 統計月度資金計划的相關信息
List<Map<String,Object>> statisticInfoByProjectId = fmexpenseplandetailService.simple(planTotalIdGroup,orgId);
if(statisticInfoByProjectId.size()!=0){
for(Map<String,Object> m:statisticInfoByProjectId){
String classId = Objects.toString(m.get("classId"), "");
Double applyMoneyByclassid= Double.parseDouble(Objects.toString(m.get("applyMoneyByclassid"), "0"));
totalMoneyForProject += applyMoneyByclassid;
// 根據 集團匯總Id planTotalIdGroup 和 orgId 獲取資金計划的子表信息
if(!"".equals(classId)){
List<Map<String,Object>> detailList = pmPayPlanService.findByplanTotalIdGroupAndOrgId(planTotalIdGroup,orgId,Long.parseLong(classId));
for(Map<String,Object> detail:detailList){
ExcelEntity a =new ExcelEntity();
a.setTopClass("項目建設支出");
a.setSecClass(Objects.toString(m.get("className"),""));
a.setSystemName(Objects.toString(detail.get("systemName"),""));
a.setApplyMoney(Objects.toString(detail.get("applyMoney"),""));
a.setDeptName(Objects.toString(detail.get("deptName"),""));
a.setReceiveUnit("");
a.setBudgetBase("");
a.setRemark(Objects.toString(detail.get("remark"),""));
result.add(a);
}
//每個收支分類的合計
ExcelEntity heji =new ExcelEntity();
heji.setTopClass("項目建設支出");
heji.setSecClass(Objects.toString(m.get("className"),""));
heji.setSystemName("合計");
heji.setApplyMoney(applyMoneyByclassid.toString());
heji.setDeptName("");
heji.setReceiveUnit("");
heji.setBudgetBase("");
heji.setRemark("");
result.add(heji);
}
}
ExcelEntity heji2 =new ExcelEntity();
heji2.setTopClass("項目建設支出");
heji2.setSecClass("合計");
heji2.setSystemName("合計");
heji2.setApplyMoney(totalMoneyForProject.toString());
heji2.setDeptName("");
heji2.setReceiveUnit("");
heji2.setBudgetBase("");
heji2.setRemark("");
result.add(heji2);
}
map.put("list", result);
//日常費用支出 + 項目建設支出總費用
Double totol = totalMoneyForProject+totalMoneyForExpense;
map.put("totol", totol.toString());
Workbook workbook = ExcelExportUtil.exportExcel(params , map);
Sheet sheetAt = workbook.getSheetAt(0);
//合並第一列
Map<Integer, int[]> mergeMap =new HashMap<>();
mergeMap.put(0, null);
// Map<Integer, int[]> mergeMap ===> key--列,value--依賴的列,沒有傳空
PoiMergeCellUtil.mergeCells(sheetAt, mergeMap, 3,sheetAt.getLastRowNum()-2);
//合並第二列
// 1、日常收支費用的合並
Map<Integer, int[]> mergeMap1 =new HashMap<>();
mergeMap1.put(1,null);
int endRow = expenseEndRow.intValue()+3-1;
PoiMergeCellUtil.mergeCells(sheetAt, mergeMap1, 3,endRow);
//合並日常收支費用的合計
CellRangeAddress region1 = new CellRangeAddress(endRow+1, endRow+1, (short) 1, (short) 2); //參數1:起始行 參數2:終止行 參數3:起始列 參數4:終止列
sheetAt.addMergedRegion(region1);
//2、項目建設的合並 (當項目建設有數據時)
if(statisticInfoByProjectId.size()!=0){
Map<Integer, int[]> mergeMap2 =new HashMap<>();
mergeMap1.put(1,null);
PoiMergeCellUtil.mergeCells(sheetAt, mergeMap1, endRow+2,sheetAt.getLastRowNum()-3);
//合並項目支出費用的合計
CellRangeAddress region2 = new CellRangeAddress(sheetAt.getLastRowNum()-2, sheetAt.getLastRowNum()-2, (short) 1, (short) 2); //參數1:起始行 參數2:終止行 參數3:起始列 參數4:終止列
sheetAt.addMergedRegion(region2);
}
//設置單元格樣式
CellStyle cellStyle = workbook.createCellStyle();//新建單元格樣式
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setWrapText(true);//設置自動換行
//為所有的單元格渲染樣式
int rowNum = sheetAt.getLastRowNum();
System.out.println(rowNum);
for(int i=3;i<rowNum;i++){
Row row = sheetAt.getRow(i);
int colNum = row.getPhysicalNumberOfCells();
for(int j=0;j<colNum;j++){
//對金錢格式進行特殊處理
if(j==3){
DataFormat dataFormat = workbook.createDataFormat();// 此處設置數據格式
cellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));
}
Cell cell = row.getCell((short) j);
cell.setCellStyle(cellStyle);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
}
return workbook;
}
效果如下:
下面是我用到的兩個合並單元格的方法
// 豎向合並相同單元格,必須保證被合並的需要有兩個及兩個以上的單元格 // Map<Integer, int[]> mergeMap ===> key--列,value--依賴的列,沒有傳空 // startRow 起始行 endRow 結束行 public static void mergeCells(Sheet sheet, Map<Integer, int[]> mergeMap, int startRow,int endRow) {} //合並一個區域類的單元格
//參數1:起始行 參數2:終止行 參數3:起始列 參數4:終止列
CellRangeAddress region = new CellRangeAddress(endRow+1, endRow+1, (short) 1, (short) 2); sheet.addMergedRegion(region);
給單元格設置樣式
HSSFCellStyle cellStyle = wb.createCellStyle(); 一、設置背景色: cellStyle.setFillForegroundColor((short) 13);// 設置背景色 cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 二、設置邊框: cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框 cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框 cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框 cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框 三、設置居中: cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中 四、設置字體: HSSFFont font = wb.createFont(); font.setFontName("黑體"); font.setFontHeightInPoints((short) 16);//設置字體大小 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗體顯示 font.setFontHeightInPoints((short) 12); cellStyle.setFont(font);//選擇需要用到的字體格式 五、設置列寬: sheet.setColumnWidth(0, 3766); //第一個參數代表列id(從0開始),第2個參數代表寬度值 參考 :"2012-08-10"的寬度為2500 六、設置自動換行: cellStyle.setWrapText(true);//設置自動換行