参考文章:(327条消息) Excel树状数据绘制导出_excel导出树形结构_Deja-vu xxl的博客-CSDN博客https://blog.csdn.net/weixin_45873182/article/details/120132409?spm=1001.2014.3001.5502
@Override
public void exportPlus(String yearMonth, HttpServletRequest request ,HttpServletResponse response) {
try {
String fileName = "周进度填报.xlsx";
ServletOutputStream out = response.getOutputStream();
HSSFWorkbook workbook = new HSSFWorkbook();
response.setHeader("content-type", "text/plain");
response.setHeader("content-type", "application/x-msdownload;");
response.setContentType("text/plain; charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
String projectId = tokenService.getProjectId(request);
List<SysDept> deptIdsByProjectId = sysDeptMapper.getDeptIdsByPeojectId(Long.valueOf(projectId));
List<SysDept> collect = deptIdsByProjectId.stream().filter(s -> s.getEmail() == null).collect(Collectors.toList());
if(collect.size()>0){
for (int i = 0; i <collect.size(); i++) {
SysDept sysDept = collect.get(i);
String email = sysDept.getEmail();
if (email == null){
exportPlusByProject(sysDept.getDeptId(),yearMonth,workbook, i, sysDept.getDeptName(), out);
}
}
}
//原理就是将所有的数据一起写入,然后再关闭输入流。
out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void exportPlusByProject(Long zhgdDeptId,String yearMonth,HSSFWorkbook workbook, int sheetNum,String sheetTitle,
String[] headers,List<List<JSONObject>> data,ServletOutputStream out) {
try {
//存放数据的二维集合,twoDimensional 中每个List是树状结构的一个分支的所有数据
List<List<JSONObject>> twoDimensional = new ArrayList<>();
//******************************查询正文数据******************************
ZhgdWeeklyProgressReport zhgdWeeklyProgressReport = new ZhgdWeeklyProgressReport();
zhgdWeeklyProgressReport.setZhgdDeptId(zhgdDeptId);
zhgdWeeklyProgressReport.setCurrentDates(yearMonth);
ZhgdWeeklyProgressReport zhgdWeeklyProgressReport1 = weeklyProgressReportService.getlastMonthData(zhgdWeeklyProgressReport);
String fillingTime1 = zhgdWeeklyProgressReport1.getFillingTime();
LambdaQueryWrapper<ZhgdWeeklyProgressReport> ZhgdWeeklyProgressReportWrapper = new LambdaQueryWrapper<>();
ZhgdWeeklyProgressReportWrapper.eq(ZhgdWeeklyProgressReport::getZhgdDeptId,zhgdDeptId)
.eq(ZhgdWeeklyProgressReport::getCurrentDates,yearMonth)
.eq(ZhgdWeeklyProgressReport::getFillingTime,fillingTime1)
.eq(ZhgdWeeklyProgressReport::getIsExists,2)
.orderByAsc(ZhgdWeeklyProgressReport::)
//------------------------------静态数据-----------------------------------
HashMap<String, Object> stringObjectHashMap0 = new HashMap<>();
stringObjectHashMap0.put("dictLabel","施工驻地,工地实验室");
stringObjectHashMap0.put("key1","39");
stringObjectHashMap0.put("key2","0.65%");
stringObjectHashMap0.put("key3","767731.2");
stringObjectHashMap0.put("key4","0.23%");
HashMap<String, Object> stringObjectHashMap1 = new HashMap<>();
stringObjectHashMap1.put("dictLabel","施工驻地,工地实验室");
HashMap<String, Object> stringObjectHashMap2 = new HashMap<>();
stringObjectHashMap2.put("dictLabel","临时工程与设施");
ArrayList<JSONObject> list0 = new ArrayList<>();
list0.add(new JSONObject(stringObjectHashMap0));
list0.add(new JSONObject(stringObjectHashMap1));
list0.add(new JSONObject(stringObjectHashMap2));
//---------------------------第二组list----------------------------------
HashMap<String, Object> stringObjectHashMap10 = new HashMap<>();
stringObjectHashMap10.put("dictLabel","拌合站(处)");
stringObjectHashMap10.put("key1","75");
stringObjectHashMap10.put("key2","1.24%");
stringObjectHashMap10.put("key3","444767731.2");
stringObjectHashMap10.put("key4","1.33%");
HashMap<String, Object> stringObjectHashMap11 = new HashMap<>();
stringObjectHashMap11.put("dictLabel","拌合站(处)");
HashMap<String, Object> stringObjectHashMap12 = new HashMap<>();
stringObjectHashMap12.put("dictLabel","临时工程与设施");
ArrayList<JSONObject> list1 = new ArrayList<>();
list1.add(new JSONObject(stringObjectHashMap10));
list1.add(new JSONObject(stringObjectHashMap11));
list1.add(new JSONObject(stringObjectHashMap12));
twoDimensional.add(list0);
twoDimensional.add(list1);
//------------------------------结束------------------------------------
//------------------------------表头-----------------------------------
//keys 是表头的字段
List<String> keys = new ArrayList<>();
//tier 是动态项目清单的总层级
Integer tier = 3;
//创建对象
//创建工作表
Sheet sheet = workbook.createSheet();
workbook.setSheetName(sheetNum, sheetTitle);
sheet.setDefaultColumnWidth(25);
short s1 = 2 * 256 ;
sheet.setDefaultRowHeight(s1);
CellStyle styleTltles = workbook.createCellStyle();
styleTltles.setFillForegroundColor(IndexedColors.GREEN.getIndex());
styleTltles.setAlignment(HorizontalAlignment.CENTER);
styleTltles.setVerticalAlignment(VerticalAlignment.CENTER);
//下边框
styleTltles.setBorderBottom(BorderStyle.THIN);
//左边框
styleTltles.setBorderLeft(BorderStyle.THIN);
//上边框
styleTltles.setBorderTop(BorderStyle.THIN);
//右边框
styleTltles.setBorderRight(BorderStyle.THIN);
//自动换行
styleTltles.setWrapText(true);
//间隔行加背景
setRowBackground(workbook);
//columnMap 是一个对象,转换成Json
//*****************************下面数据请求数据库***********************
LambdaQueryWrapper<ZhgdWeeklyProgressReport> weeklyProgressReportLambdaQueryWrapper = new LambdaQueryWrapper<>();
weeklyProgressReportLambdaQueryWrapper.eq(ZhgdWeeklyProgressReport::getCurrentDates,yearMonth)
.eq(ZhgdWeeklyProgressReport::getZhgdDeptId,zhgdDeptId)
.groupBy(ZhgdWeeklyProgressReport::getFillingTime)
.groupBy(ZhgdWeeklyProgressReport::getCreateDatetime)
.orderByAsc(ZhgdWeeklyProgressReport::getCreateDatetime)
.select(ZhgdWeeklyProgressReport::getFillingTime);
List<ZhgdWeeklyProgressReport> weeklyProgressReportList = weeklyProgressReportService.list(weeklyProgressReportLambdaQueryWrapper);
HashMap<String, Object> columnMap = new HashMap<>(5);
columnMap.put("单价(元)","单价(元)");
keys.add("单价(元)");
columnMap.put("总量","总量");
keys.add("总量");
if (weeklyProgressReportList.size()>0){
weeklyProgressReportList.stream().forEach(entity->{
String fillingTime = entity.getFillingTime();
String s = fillingTime + "日完成工程量";
columnMap.put(s,s);
keys.add(s);
});
}
columnMap.put("完成工程量合计","完成工程量合计");
keys.add("完成工程量合计");
if (weeklyProgressReportList.size()>0){
weeklyProgressReportList.stream().forEach(entity->{
String fillingTime = entity.getFillingTime();
String s = fillingTime + "日完成产值(万元)";
columnMap.put(s,s);
keys.add(s);
});
}
columnMap.put("完成产值(万元)合计","完成产值(万元)合计");
keys.add("完成产值(万元)合计");
columnMap.put("截止上月累计完成工程量","截止上月累计完成工程量");
keys.add("截止上月累计完成工程量");
columnMap.put("截止上月累计完成产值","截止上月累计完成产值");
keys.add("截止上月累计完成产值");
columnMap.put("截止本月累计完成工程量","截止本月累计完成工程量");
keys.add("截止本月累计完成工程量");
columnMap.put("累计完成总量占比","累计完成总量占比");
keys.add("累计完成总量占比");
columnMap.put("截止本月累计完成产值(万元)","截止本月累计完成产值(万元)");
keys.add("截止本月累计完成产值(万元)");
//动态创建首行表头
JSONObject topBean = new JSONObject();
Row firstRow = sheet.createRow(0);
JSONObject cm = new JSONObject(columnMap);
for (int i = 0; i < tier+keys.size(); i++) {
Cell cell = firstRow.createCell(i);
if (i<tier){
String s="一";
switch (i){
case 1 : s="二";break;
case 2 : s="三";break;
}
cell.setCellValue(s+"级分类");
}else {
cell.setCellValue(cm.getString(keys.get(i - tier)));
}
}
//动态绘制数据,tier是层级数,根据业务最多三级
for (int i = 0; i < twoDimensional.size(); i++) {
Row row = sheet.createRow(i+1);
List<JSONObject> list = twoDimensional.get(i);
for (int j = 0; j < keys.size()+tier; j++) {
Cell cell = row.createCell(j);
if (j<tier){
//绘制层级标签
if (j==0){
JSONObject jsonObject = list.get(tier - 1);
cell.setCellValue(jsonObject.getString("dictLabel"));
continue;
}
if (j==1){
Map map = list.get(tier - 2);
cell.setCellValue((String)map.get("dictLabel"));
continue;
}
if (j==2){
Map map = list.get(tier - 3);
cell.setCellValue((String)map.get("dictLabel"));
continue;
}
}else {
//绘制层级的数据
JSONObject bean = new JSONObject(list.get(0));
cell.setCellValue(bean.getString(keys.get(j - tier)));
}
}
}
//添加总合计行,并合并单元格
Row totalRow = sheet.createRow(twoDimensional.size()+1);
for (int j = 0; j < keys.size()+tier; j++) {
Cell cell = totalRow.createCell(j);
if (j<tier){
cell.setCellValue("合计");
}else {
cell.setCellValue(topBean.getString(keys.get(j - tier)));
}
}
if (tier != 1){
sheet.addMergedRegion(new CellRangeAddress(twoDimensional.size()+1,twoDimensional.size()+1,0,tier-1));
}
//合并相同的单元格
int lastRowNum = sheet.getLastRowNum();
int index = 0;
//根据业务只有标签这几列需要合并
for (int i = 0; i < tier-1; i++) {
//比较相邻cell的值是否相同,并记录
for (int j = 0; j < lastRowNum; j++) {
Row row = sheet.getRow(j);
Cell cell = row.getCell(i);
Cell cell2 = row.getCell(i+1);
String stringCellValue = cell.getStringCellValue();
String stringCellValueNextRow = cell2.getStringCellValue();
if ("合计".equals(stringCellValue)){
sheet.addMergedRegion(new CellRangeAddress(j,j,i,i+1));
continue;
}
Row nextRow = sheet.getRow(j+1);
Cell nextcell = nextRow.getCell(i);
String nextStringCellValue = nextcell.getStringCellValue();
if (stringCellValue.equals(nextStringCellValue)){
if (j+1 == lastRowNum){
if (index != 0){
sheet.addMergedRegion(new CellRangeAddress(j-index,j+1,i,i));
index = 0;
}
}else {
index++;
}
}else {
if (index != 0){
sheet.addMergedRegion(new CellRangeAddress(j-index,j,i,i));
index = 0;
}
}
//横向合并
// row-- 相邻的如果相同合并
if (stringCellValueNextRow.equals(stringCellValue) && j != 0 ){
sheet.addMergedRegionUnsafe(new CellRangeAddress(j,j,i,i+1));
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
导出样式