easyExcel模版示例地址:

接下来代码展示

1.添加easyExcel依赖

 <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.3</version></dependency>

2.创建一个类似于实体的Bean

package com.zykj.common.util.bean;import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.Data;import java.math.BigDecimal;@Data
public class ExportReconciliationClearFormBean {//标题public String title;//序号public int number;//日期public String date;//业务系统人数public int number_of_business_system;//业务系统金额public BigDecimal business_system_amount;//财务到账人数public int number_of_people_in_the_account;//财务到账金额public BigDecimal financial_receipt_amount;//人数差异public int poor_number_of_people;//金额差异public BigDecimal difference_in_amount;//业务系统人数合计public int yw_people_count;//业务系统金额合计public BigDecimal yw_amount_count;//财务到账人数合计public int cw_people_count;//财务到账金额合计public BigDecimal cw_amount_count;//人数差异合计public int poor_number_of_people_count;//金额差异合计public BigDecimal difference_in_amount_count;//备注public String remarks;//这里省略了get和set方法 记得添加}
}

3.根据你的需求创建摸版

{xxx}是Map填充 xxx对应key value放所对应的值
{.xxx}是list填充 xxx对应着list的名称 如果是list<上面创建的bean> 那xxx对应bean的属性

4.后台Controller代码

/*** 导出对账确认表* qyh*/public void exportReconciliationClearForm() throws IOException, ParseException {Map<String,Object> map = new HashMap<>();List<ExportReconciliationClearFormBean> bean = new ArrayList<ExportReconciliationClearFormBean>();String date = getPara("date");SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//开始时间String tartingTime = date.substring(0,date.indexOf(" -"));//结束时间String endTime = date.substring(date.lastIndexOf("- ")+1,date.length());//系统类型 1职称 2计算机英语 3协会String orderType = getPara("orderType");map.put("tartingTime",sdf.parse(tartingTime.replace("/","-")));map.put("endTime",sdf.parse(endTime.replace("/","-")));map.put("orderType",orderType);int randInt = (int) ((Math.random() * 9 + 1) * 1000);String fileName = RdmUtils.replaceSign(endTime)+ randInt + ".zip";getResponse().setContentType("APPLICATION/OCTET-STREAM");//b.Content-Disposition 设置要被下载的文件名getResponse().setHeader("Content-Disposition", "attachment;filename=" + fileName);//获取输出流ServletOutputStream out = getResponse().getOutputStream();//计算机英语系统  报名 用书 证书String computerEnglish = getPara("orderTypeTwo");String[] computerEnglishType = computerEnglish.split(",");List<File> listFile = new ArrayList<>();if(orderType.equals("1")){Map<String,Object> orderMap = orderService.exportReconciliationClearForm(map);bean = (List<ExportReconciliationClearFormBean>) orderMap.get("bean");orderMap.remove("bean");orderMap.put("orderType",orderType);File file = ExportUtils.ExportReconciliationClearForm(orderMap,bean);listFile.add(file);//给文件打成zip包(如果不需要打成压缩包就不需要,直接返回file文件就可)ZipUtils.toZip(listFile,out);}else if(orderType.equals("2")){for (int i = 0;i<computerEnglishType.length;i++){String type = computerEnglishType[i];if(type.equals("1")){map.put("type",type);Map<String,Object> orderMap = orderService.exportReconciliationClearForm(map);bean = (List<ExportReconciliationClearFormBean>) orderMap.get("bean");orderMap.remove("bean");orderMap.put("orderType",orderType);orderMap.put("type",type);File file = ExportUtils.ExportReconciliationClearForm(orderMap,bean);listFile.add(file);}else if(type.equals("2")){map.put("type",type);Map<String,Object> orderMap = orderService.exportReconciliationClearForm(map);bean = (List<ExportReconciliationClearFormBean>) orderMap.get("bean");orderMap.remove("bean");orderMap.put("orderType",orderType);orderMap.put("type",type);File file = ExportUtils.ExportReconciliationClearForm(orderMap,bean);listFile.add(file);}else if(type.equals("3")){map.put("type",type);Map<String,Object> orderMap = orderService.exportReconciliationClearForm(map);bean = (List<ExportReconciliationClearFormBean>) orderMap.get("bean");orderMap.remove("bean");orderMap.put("orderType",orderType);orderMap.put("type",type);File file = ExportUtils.ExportReconciliationClearForm(orderMap,bean);listFile.add(file);}}ZipUtils.toZip(listFile,out);}else if(orderType.equals("3")){Map<String,Object> orderMap = orderService.exportReconciliationClearForm(map);bean = (List<ExportReconciliationClearFormBean>) orderMap.get("bean");orderMap.remove("bean");orderMap.put("orderType",orderType);File file = ExportUtils.ExportReconciliationClearForm(orderMap,bean);listFile.add(file);ZipUtils.toZip(listFile,out);}renderNull();}

5.附上打zip压缩包代码

 private static final int BUFFER_SIZE = 2 * 1024;/*** 压缩成ZIP** @param srcFiles*            需要压缩的文件列表* @param out*            压缩文件输出流* @throws RuntimeException*             压缩失败会抛出运行时异常*/public static void toZip(List<File> srcFiles, OutputStream out)throws RuntimeException {long start = System.currentTimeMillis();ZipOutputStream zos = null;try {zos = new ZipOutputStream(out);for (File srcFile : srcFiles) {byte[] buf = new byte[BUFFER_SIZE];zos.putNextEntry(new ZipEntry(srcFile.getName()));int len;FileInputStream in = new FileInputStream(srcFile);while ((len = in.read(buf)) != -1) {zos.write(buf, 0, len);}zos.closeEntry();in.close();}long end = System.currentTimeMillis();System.out.println("压缩完成,耗时:" + (end - start) + " ms");} catch (Exception e) {throw new RuntimeException("zip error from ZipUtils", e);} finally {if (zos != null) {try {zos.close();} catch (IOException e) {e.printStackTrace();}}}}

6.模版填充

ExcelWriter excelWriter = EasyExcel.write(excelFile).registerWriteHandler(new History2014ExportCellWriteHandler()).withTemplate(templateFileName).build(); 如果你看过官方的文档会发现多了一个.registerWriteHandler(new History2014ExportCellWriteHandler()),这是给导出的Excel设置样式,下面有样式的代码


public static File ExportReconciliationClearForm(Map<String, Object> map, List<ExportReconciliationClearFormBean> list){// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替// {} 代表普通变量 {.} 代表是list的变量String templateFileName = PathKit.getWebRootPath() + File.separator + "Template" + File.separator + "exportReconciliationClearForm.xls";String orderType = (String) map.get("orderType");String path = "";String title = "";if(orderType.equals("1")){path = "XX系统收费对账确认表";title = "XX系统收费对账确认表";}else if(orderType.equals("2")){String orderTypeTwo = (String) map.get("type");if(orderTypeTwo.equals("1")){path = "XX系统收费对账确认表(考试报名)";title = "XX系统收费对账确认表(考试报名)";}else if(orderTypeTwo.equals("2")){path = "XX系统收费对账确认表(考试用书)";title = "XX系统收费对账确认表(考试用书)";}else if(orderTypeTwo.equals("3")){path = "XX系统收费对账确认表(考试证书)";title = "XX系统收费对账确认表(考试证书)";}}else if(orderType.equals("3")){path = "XX系统收费对账确认表";title = "XX系统收费对账确认表";}//地址 根据自己的项目地址设置String baseDownPath = AppConfig.baseDownPath;File excelFile = new File(PathKit.getWebRootPath() + File.separator + baseDownPath + File.separator + "Template" + File.separator + path + ".xls");ExcelWriter excelWriter = EasyExcel.write(excelFile).registerWriteHandler(new History2014ExportCellWriteHandler()).withTemplate(templateFileName).build();WriteSheet writeSheet = EasyExcel.writerSheet().build();// 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。// forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了,所以慎用// 简单的说 如果你的模板有list,且list不是最后一行,下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存// 如果数据量大 list不是最后一行 参照下一个FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();//放入的是list列表中的数据excelWriter.fill(list, fillConfig, writeSheet);map.put("title", title);//map中的数据excelWriter.fill(map, writeSheet);excelWriter.finish();return excelFile;}

7.设置样式代码

根据需求更改自己的样式设置列宽,行高等

package com.zykj.common.util;import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.*;import javax.swing.*;
import java.util.List;/**
* 设置样式
* qyh
*/
public class History2014ExportCellWriteHandler implements CellWriteHandler {@Overridepublic void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {}@Overridepublic void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}@Overridepublic void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}@Overridepublic void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {Workbook workbook = writeSheetHolder.getSheet().getWorkbook();CellStyle cellStyle = workbook.createCellStyle();Font font = workbook.createFont();if (cell.getRowIndex() == 0) {font.setFontHeightInPoints((short) 18);font.setFontName("宋体");font.setBold(true);cellStyle.setFont(font);cellStyle.setAlignment(HorizontalAlignment.CENTER);cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置 自动换行cellStyle.setWrapText(true);Row row = cell.getRow();row.setHeightInPoints(27);} else if (cell.getRowIndex() == 1) {font.setFontHeightInPoints((short) 11);font.setFontName("宋体");cellStyle.setBorderBottom(BorderStyle.NONE);cellStyle.setBorderLeft(BorderStyle.THIN);cellStyle.setBorderRight(BorderStyle.THIN);cellStyle.setBorderTop(BorderStyle.THIN);font.setBold(false);cellStyle.setFont(font);cellStyle.setAlignment(HorizontalAlignment.LEFT);cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置 自动换行cellStyle.setWrapText(true);Row row = cell.getRow();row.setHeightInPoints(27);} else if (cell.getRowIndex() == 2) {//设置边框cellStyle.setBorderBottom(BorderStyle.NONE);cellStyle.setBorderLeft(BorderStyle.THIN);cellStyle.setBorderRight(BorderStyle.THIN);cellStyle.setBorderTop(BorderStyle.THIN);//设置字体大小font.setFontHeightInPoints((short) 12);//设置字体样式font.setFontName("宋体");//设置加粗font.setBold(false);//设置字体样式cellStyle.setFont(font);//设置  文字左右居中  【水平居中需要使用以下两行】cellStyle.setAlignment(HorizontalAlignment.CENTER);//设置文字居中  上下居中cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置 自动换行cellStyle.setWrapText(true);//获取行Row row = cell.getRow();//设计行高row.setHeightInPoints(27);} else {//设置边框cellStyle.setBorderBottom(BorderStyle.THIN);cellStyle.setBorderLeft(BorderStyle.THIN);cellStyle.setBorderRight(BorderStyle.THIN);cellStyle.setBorderTop(BorderStyle.THIN);//居中cellStyle.setAlignment(HorizontalAlignment.CENTER);cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);Row row = cell.getRow();//设计行高row.setHeightInPoints(27);}cell.setCellStyle(cellStyle);}
}

8.我的导出结果

结束语

希望本文可以帮到大家,当然也有很多不足,希望大佬可以多多提意见,一起进步!!!

阿里EasyExcel对Excel复杂模版填充实现并设置单元格格式相关推荐

  1. Web中的EasyExcel导出Excel(不创建对象且自定义合并单元格策略)

    Web中的EasyExcel导出Excel(不创建对象且自定义合并单元格策略) 适用于多张表(只查单表数据就用创建对象那种方法) Controller @RequestMapping(value = ...

  2. aspose 换行写_Aspose.Cells 首次使用,用到模版填充数据,合并单元格,换行

    Aspose.Cells 首次使用,用到模版填充数据,合并单元格,换行 模版格式,图格式是最简单的格式,但实际效果不是这种,实际效果图如图2 image 图2 ,注意看红色部分,一对一是正常的,但是有 ...

  3. 设置单元格填充方式_单元格的选择及设置单元格格式

    数据输入完毕,接下来可以设置字体.对齐方式.添加边框和底纹等方式设置单元格格式,从而美化工作表.要对单元格进行设置,首先要选中单元格. 选择单元格 选择单元格是指在工作表中确定活动单元格以便在单元格中 ...

  4. datagridview单元格合并居中_系统地学习Excel第17课,设置单元格格式

    上一篇:系统地学习Excel第16课,使用Excel的「替换」功能 本篇内容结构如下: 本章的知识体系 Excel工作表的整体外观由各个单元格的样式构成,单元格的样式外观在Excel的可选设置中主要包 ...

  5. Python 操作 excel 插入图片、表格、设置单元格颜色、字体(三)

    Python 操作 excel 插入图片.表格.设置单元格颜色.字体 python 操作 excel 插入图片.表格.设置单元格颜色.字体 提示:以下是本篇文章正文内容,下面案例可供参考 一.open ...

  6. java导出excel表格设置行高,POI导出Excel设置单元格格式

    使用Apache的POI相关API导出Excel设置单元格格式 栗子,一下各个代码之间的变量是通用的,要是在某个代码块中找不到某个变量,则可以向上找寻 准备工作 InputStream = templ ...

  7. 支持将数据导出到Excel文档的时候设置单元格格式的.NET控件Spire.DataExport

    Spire.DataExport for .NET是e-iceblue公司推出的一款数据导出类.NET控件.作为一款专业的数据导出控件,Spire.DataExport for .NET可以帮助开发人 ...

  8. html导出excel合并单元格,JS导出EXCEL,动态设置单元格格式,合并单元格(横向或纵向)等操作...

    参考链接: https://blog.csdn.net/weixin_33724046/article/details/89611397 https://www.cnblogs.com/lvsk/p/ ...

  9. java poi设置单元格格式为数值_java中导出excel设置单元格的样式为数字格式怎么设置_Java代码实现设置单元格格式...

    java中导出excel设置单元格的样式为数字格式怎么设置 如果是使用poi,它会自动根据参数值设置单元格为恰当格式,只需传入数字类型参数值即可,比如 double value=....; cell. ...

最新文章

  1. 【转】堆栈和托管堆 c#
  2. 对称加密算法 - Java加密与安全
  3. 数据库基本常用类型解析
  4. linux执行db2的sql脚本,LinuxShell自动执行当前目录所有DB2 SQL语句
  5. 每天一个linux命令:du 与 df
  6. django 1.11.16之环境搭建
  7. mfsort shell语法_8.10 shell特殊符号cut命令 8.11 sort_wc_uniq命令 8.12 tee_tr_split命令 8.13 shell特殊符号下...
  8. 从零开始撸一个ajax框架
  9. 服务器上怎么安虚拟主机呀,上线虚拟主机产品步骤
  10. 《赖氏经典英语语法》第一集
  11. pyqt 事件更新图片显示_暗黑战神3D网游ARPG实战案例(Unity 2017.3)更新
  12. Java中级内容——异常处理(exception handing)
  13. 有没有ai绘画教程?什么软件能实现ai绘画?
  14. Spring-Bean加载顺序控制/循环依赖控制
  15. python趋势回归_python使用LASSO回归预测股票收益
  16. css 中英文换行的相关写法
  17. XX^{T} 和 X^{T}X 的关系
  18. mysql获取后两位_Mysql 截取保留小数点后两位内容
  19. 数据结构(数组结构、链表结构)
  20. 大数据技术原理与应用(7-11)-TYUT

热门文章

  1. 大调查:7成网友呼吁共享单车免押金和上保险
  2. iOS转场动画之微信朋友圈图片查看器
  3. 2022第九届生物发酵展(济南)3月召开,拓展生物发酵行业新机遇
  4. win7、win10安装Microsoft Loopback 接口
  5. python循环代码优化技巧_记一次优化python循环代码逻辑的过程
  6. 爬虫大作业-爬取B站弹幕
  7. (NO.00005)iOS实现炸弹人游戏(一):游戏的整体规划设计
  8. My SQL 排序和分组
  9. CentOS7 python gi模块安装
  10. 使用思维导图进行产品需求分析