Java使⽤EasyExcel导出⼯具类(实体类,⾮实体类,List<Map<String。。
。
〇:⼯具类内容
1.先引⽤l
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
<scope>compile</scope>
</dependency>
<!--阿⾥巴巴导出 easyexcel jar-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
2、定义两个实体类
⾃⾏⾃动⽣成get,set⽅法
public class NoModelWriteData implements Serializable {
private String fileName;//⽂件名
private String[] headMap;//表头数组
private String[] dataStrMap;//对应数据字段数组
private List<Map<String, Object>> dataList;//数据集合
}
public class SimpleWriteData implements Serializable {
private String fileName;//⽂件名
private List<?> dataList;//数据列表
}
3、添加⼯具类内容
import EasyExcel;
import ExcelWriter;
import ExcelTypeEnum;
import WriteSheet;
import JSON;
import HttpHeaders;
import NoModelWriteData;
import SimpleWriteData;
import T;
import RequestBody;
import HttpServletResponse;
import IOException;
import URLEncoder;
import*;
public class EasyExcelUtils {
//不创建对象的导出
public void noModleWrite(@RequestBody NoModelWriteData data, HttpServletResponse response)throws IOException {
// 这⾥注意有同学反应使⽤swagger 会导致各种问题,请直接⽤浏览器或者⽤postman
try{
// response.setContentType("application/vnd.ms-excel");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这⾥de可以防⽌中⽂乱码当然和easyexcel没有关系
// 这⾥de可以防⽌中⽂乱码当然和easyexcel没有关系
String fileName = FileName(),"UTF-8");
response.setHeader("Content-disposition","attachment;filename="+ fileName +".xlsx");
// 这⾥需要设置不关闭流
EasyExcel.OutputStream()).head(HeadMap())).FileName()).doWrite(DataList(), DataStrMap()));
}catch(Exception e){
// 重置response
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map =new HashMap<String, String>();
map.put("status","failure");
map.put("message","下载⽂件失败"+ e.getMessage());
}
}
//创建对象的导出
public<T>void simpleWrite(@RequestBody SimpleWriteData data,Class<T> clazz, HttpServletResponse response)throws IOException {
// 这⾥注意有同学反应使⽤swagger 会导致各种问题,请直接⽤浏览器或者⽤postman
// response.setContentType("application/vnd.ms-excel");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这⾥de可以防⽌中⽂乱码当然和easyexcel没有关系
String fileName = FileName(),"UTF-8");
response.setHeader("Content-disposition","attachment;filename="+ fileName +".xlsx");
EasyExcel.OutputStream(), clazz).FileName()).DataList());
}
//设置表头
private List<List<String>>head(String[] headMap){
List<List<String>> list =new ArrayList<List<String>>();
for(String head : headMap){
List<String> headList =new ArrayList<String>();
headList.add(head);
list.add(headList);
}
return list;
}
//设置导出的数据内容
private List<List<Object>>dataList(List<Map<String, Object>> dataList, String[] dataStrMap){
List<List<Object>> list =new ArrayList<List<Object>>();
for(Map<String, Object> map : dataList){
List<Object> data =new ArrayList<Object>();
for(int i =0; i < dataStrMap.length; i++){
data.(dataStrMap[i]));
}
list.add(data);
}
return list;
}
}
⼀:不使⽤实体类导出
这⾥只针对接⼝返回的List<Map<String,Object>>类型数据做后续操作,跟随⽂章的步骤操作即可
1、查询数据
如图获取了List<Map<String, Object>>类型的数据
2、定义数组
headMap数组定义的是导出⽂件表头标题的内容,要按顺序定义
dataStrMap数据定义的是标题对应的字段名(⼀定要按顺序对应)
String[] headMap ={"项⽬名称","楼栋名称","单元名称","楼层名称","房间名称","业主/租户姓名","房间状态","房间功能","认证⼈数"}; String[] dataStrMap={"hName","bName","uName","fName","pName","cName","pState","pFunction","pNum"};
3、将数据放⼊⼯具类⽅法的实体类中
NoModelWriteData d =new NoModelWriteData();
d.setFileName("认证统计");
d.setHeadMap(headMap);
d.setDataStrMap(dataStrMap);
d.setDataList(listDatas);
EasyExcelUtils easyExcelUtils =new EasyExcelUtils();
⼆:使⽤实体类导出
1、定义数据实体类
⾃⾏⾃动⽣成get,set⽅法,这⾥就不放出来了
实体类中的注解可以根据⾃⼰的需求使⽤,更多注解可查看⽂章开头的官⽅⽰例⽂档
@Data
public class PayInfoBillListExportDto implements Serializable {
@ExcelProperty("项⽬名称")
private String hName;
@ExcelProperty("楼栋名称")
private String bName;
@ExcelProperty("单元名称")
private String uName;
@ExcelProperty("楼层名称")
private String fName;
@ExcelProperty("房间名称")
private BigDecimal pName;
@ExcelProperty("业主/租户姓名")
private BigDecimal cName;
@ExcelProperty("房间状态")
private BigDecimal pState;
@ExcelProperty("房间功能")
private BigDecimal pFunction;
@ExcelProperty("认证⼈数")
private String pNum;
// @ExcelIgnore 此注解表⽰忽略这个字段
// @DateTimeFormat("yyyy年MM⽉dd⽇HH时mm分ss秒") 时间格式化注解
// @NumberFormat("#.##%") 百分⽐表⽰
// @ColumnWidth(50) 设置单元格宽度为50
// @ExcelProperty(value = "标题", index = 0) 第0列为标题列
}
1、查询数据
2、将数据放⼊⼯具类⽅法的实体类中
SimpleWriteData d =new SimpleWriteData();
d.setFileName("认证统计");
d.setDataList(list);
EasyExcelUtils easyExcelUtils =new EasyExcelUtils();
easyExcelUtils.simpleWrite(d,PayInfoBillListExportDto.class,response);
此⼯具类只针对这两种数据进⾏封装
补充
但是在任务过程中,⽣成的⽂档的格式要求并不符合产品和测试的期望值 如图:
经过百度⼯程师的各种挑战实验和查阅实现了此功能
Excel⽂档的⾃动列宽设置
//Excel⽂档的⾃动列宽设置
public class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
private static final int MAX_COLUMN_WIDTH =255;
//因为在⾃动列宽的过程中,有些设置地⽅让列宽显得紧凑,所以做出了个判断
private static final int COLUMN_WIDTH =2;
private Map<Integer, Map<Integer, Integer>> CACHE =new HashMap(8);
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolea n isHead){
boolean needSetWidth = isHead ||!CollectionUtils.isEmpty(cellDataList);
if(needSetWidth){
Map<Integer, Integer> maxColumnWidthMap =((SheetNo());
if(maxColumnWidthMap ==null){
maxColumnWidthMap =new HashMap(16);
CACHE.SheetNo(), maxColumnWidthMap);
}
Integer columnWidth =this.dataLength(cellDataList, cell, isHead);
if(columnWidth >=0){
if(columnWidth > MAX_COLUMN_WIDTH){
columnWidth = MAX_COLUMN_WIDTH;
}else{
if(columnWidth<COLUMN_WIDTH){
columnWidth =columnWidth*2;
}
}
Integer maxColumnWidth =(Integer)((Map)maxColumnWidthMap).ColumnIndex());
if(maxColumnWidth ==null|| columnWidth > maxColumnWidth){
((Map)maxColumnWidthMap).ColumnIndex(), columnWidth);
}
}
}
}
private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead){
if(isHead){
StringCellValue().getBytes().length;
}else{
CellData cellData =((0);
CellDataTypeEnum type = Type();
if(type ==null){
return-1;
}else{
switch(type){
case STRING:
StringValue().getBytes().length;
case BOOLEAN:
BooleanValue().toString().getBytes().length;
case NUMBER:
NumberValue().toString().getBytes().length;
default:
return-1;
}
}
}
}
//Excel的字体,样式,背景⾊的设置 public static HorizontalCellStyleStrategy getStyleStrategy(){ // 头的策略 WriteCellStyle headWriteCellStyle = new WriteCellStyle(); // 背景设置为灰⾊ headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_Index()); WriteFo nt headWriteFont = new WriteFont(); // 字体样式 headWriteFont.setFontName("Frozen"); headWriteFont.setFontHeightInPoints((short)12); headWriteFont.setBold(true); headWriteCellStyle.setWriteFont(headWriteFont); //⾃动换⾏ headWriteCellStyle.setWrapped(false); // ⽔平对齐⽅式 headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); // 垂直对齐⽅式 headWriteCellStyle.setVerticalAlignme nt(VerticalAlignment.CENTER); // 内容的策略 WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); // 这⾥需要指定 FillPatternType 为Fil lPatternType.SOLID_FOREGROUND 不然⽆法显⽰背景颜⾊.头默认了 FillPatternType所以可以不指定// contentWriteCellStyle.setFillPatternType(FillPatt ernType.SQUARES); // 背景⽩⾊ contentWriteCellStyle.setFillForegroundColor(Index()); WriteFont contentWriteFon t = new WriteFont(); // 字体⼤⼩ contentWriteFont.setFontHeightInPoints((short)12); // 字体样式 contentWriteFont.setFontNa
me("Calibri"); contentWriteCellStyle.setWriteFont(contentWriteFont); // 这个策略是头是头的样式内容是内容的样式其他的策略可以⾃⼰实现 return new Hor izontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); }}
调⽤⽅式
这部分是因为我的Excel都是⾃定义开头数据,所以⽤的是List<Map<String, Object>>
EasyExcel.OutputStream())
.head(HeadMap()))
.registerWriteHandler(new ExcelWidthStyleStrategy())
.StyleStrategy())
.FileName())
.doWrite(DataList()
,DataStrMap()));
下⾯部分是⽤上实体类的调⽤
java switch case stringEasyExcel.write(outputStream).needHead(true)
.head(clazz)
.excelType(ExcelTypeEnum.XLSX)
.registerWriteHandler(new Custemhandler())
.StyleStrategy())
.sheet(0, sheetName)
.doWrite(writeList);
修改后
⼯具类内容
import EasyExcel;
import JSON;
import NoModelWriteData;
import SimpleWriteData;
import URLEncoder;
import RequestBody;
import HttpServletResponse;
import IOException;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论