当前位置:网站首页>Easypoi --- excel file export
Easypoi --- excel file export
2022-07-28 17:04:00 【Zhengx Hui】
One .pom The file import jar
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>Two . Create a tool class
public class ExcelUtils {
/**
* excel export
*
* @param list Data to export
* @param pojoClass pojo type
* @param fileName File name
* @param exportParams Export table parameters
* @param response
*/
public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams,
HttpServletResponse response) throws IOException {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
public static void exportExcel(ExportParams exportParams, List<ExcelExportEntity> colList, List<?> list,HttpServletResponse response)
throws IOException {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, colList, list);
downLoadExcel(exportParams.getSheetName(), response, workbook);
}
/**
* Download the file
*
* @param fileName File name
* @param response
* @param workbook excel data
*/
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)
throws IOException {
try {
response.setHeader("Access-Control-Allow-Origin","*");
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
OutputStream output=response.getOutputStream();
workbook.write(output);
output.flush();
workbook.close();
output.close();
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
}
3、 ... and . Create entity class
public class ElePfvEnergyDTO implements Serializable{
private static final long serialVersionUID = 1L;
@Excel(name = " Process name ", width = 20)
private String name;
@Excel(name = " Electric quantity ", groupName = " tip ", width = 20, orderNum = "0")
private Double top;
@Excel(name = " Electricity fees ", groupName = " tip ", width = 20, orderNum = "1")
private Double topCost;
@Excel(name = " Electric quantity ", groupName = " high ", width = 20, orderNum = "0")
private Double high;
@Excel(name = " Electricity fees ", groupName = " high ", width = 20, orderNum = "1")
private Double highCost;
@Excel(name = " Electric quantity ", groupName = " flat ", width = 20, orderNum = "0")
private Double flat;
@Excel(name = " Electricity fees ", groupName = " flat ", width = 20, orderNum = "1")
private Double flatCost;
@Excel(name = " Electric quantity ", groupName = " valley ", width = 20, orderNum = "0")
private Double valley;
@Excel(name = " Electricity fees ", groupName = " valley ", width = 20, orderNum = "1")
private Double valleyCost;
@Excel(name = " Electric quantity ", groupName = " A total of ", width = 20, orderNum = "0")
private Double allEle;
@Excel(name = " Electricity fees ", groupName = " A total of ", width = 20, orderNum = "1")
private Double allCost;
}
Four . stay ExportParams Class , find ExcelExportStylerDefaultImpl class , Copy the content and generate new classes ( Used to set excel Header background , typeface , Location, etc )

/**
* The default implementation of style
* @author JueYue
* 2015 year 1 month 9 Japan Afternoon 5:36:08
*/
public class ExcelExportStylerImpl extends AbstractExcelExportStyler
implements IExcelExportStyler {
public ExcelExportStylerImpl(Workbook workbook) {
super.createStyles(workbook);
}
@Override
public CellStyle getTitleStyle(short color) {
CellStyle titleStyle = workbook.createCellStyle();
Font font = this.workbook.createFont();
font.setBold(true);
titleStyle.setFont(font);
titleStyle.setAlignment(HorizontalAlignment.CENTER);
titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
titleStyle.setWrapText(true);
titleStyle.setBorderRight(BorderStyle.THIN);
titleStyle.setBorderTop(BorderStyle.THIN);
titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
return titleStyle;
}
@Override
public CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setDataFormat(STRING_FORMAT);
if (isWarp) {
style.setWrapText(true);
}
return style;
}
@Override
public CellStyle getHeaderStyle(short color) {
CellStyle titleStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 12);
titleStyle.setFont(font);
return titleStyle;
}
@Override
public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setDataFormat(STRING_FORMAT);
if (isWarp) {
style.setWrapText(true);
}
return style;
}
}
5、 ... and .controller Layer calls
@RequestMapping(value = "/exportPFYXls")
public void exportXls(HttpServletResponse response) {
List<ElePfvEnergyDTO> list = service.getAreaCodeList();
String fileName = " A detailed list ";
String sheetName = " A detailed list ";
ExportParams exportParams = new ExportParams();
exportParams.setSheetName(sheetName);
exportParams.setStyle(ExcelExportStylerImpl.class);
exportParams.setCreateHeadRows(true);
exportParams.setHeaderHeight(500D);
try {
ExcelUtils.exportExcel(list,ElePfvEnergyDTO.class,fileName,exportParams,response);
} catch (Exception e) {
e.printStackTrace();
}
}6、 ... and . Exhibition :

7、 ... and : Vertical cell merging
excel There are two attributes in the annotation NeedMerge: Whether to merge ; MergeVertical: Vertical merger
@Excel(name = " Electric quantity ", groupName = " tip ", width = 20, orderNum = "0" ,mergeVertical = true, needMerge = true)8、 ... and . Dynamic meter :
1. Manually splice the meter :
public List<ExcelExportEntity> getHeadList(EnParamsVo vo){
List<String> dateList = new ArrayList<String>();
for (int i = 0; i < vo.getSelCount(); i++) {
String thisDay = DateUtil.getSpecifiedDayBefore(vo.getSelDate(), i);
dateList.add(thisDay);
}
Collections.reverse(dateList);
List<ExcelExportEntity> colList = new ArrayList<ExcelExportEntity>();
// First column
ExcelExportEntity colEntity1 = new ExcelExportEntity(" name ", "name");
colEntity1.setNeedMerge(true);
colEntity1.setMergeVertical(true);
colList.add(colEntity1);
// Second column
ExcelExportEntity colEntity2 = new ExcelExportEntity(" Category ", "type");
colEntity2.setNeedMerge(true);
colList.add(colEntity2);
for(String localDate:dateList){
ExcelExportEntity dateColGroup = new ExcelExportEntity(localDate, localDate);
List<ExcelExportEntity> dateColList = new ArrayList<ExcelExportEntity>();
ExcelExportEntity tempExcelExportEntity = new ExcelExportEntity(DateUtil.getWeekOfDate(localDate), "dayOfWeek"+localDate);
dateColList.add(tempExcelExportEntity);
dateColGroup.setList(dateColList);
colList.add(dateColGroup);
}
return colList;
}2. Manual splicing value :
public List<Map<String, Object>> getExcelList(Map<String, Object> map, String name) {
List<String> dateList = (List<String>) map.get("xList");
List<String> outputList = (List<String>) map.get("outputList");
List<String> electricList = (List<String>) map.get("electricList");
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
List<String> typeList = Arrays.asList("test1","test2","test3","test4","test5","test6");
for(int i=0;i < typeList.size();i++){
Map<String, Object> valMap = new HashMap<>();
valMap.put("name", name);
valMap.put("type",typeList.get(i));
for(int j=0;j < dateList.size();j++){
List<Map<String, Object>> dayOfWeekList = new ArrayList<Map<String, Object>>();
Map<String, Object> dayOfWeekMap = new HashMap<String, Object>();
if (i == 1) {
dayOfWeekMap.put("dayOfWeek"+ dateList.get(j), outputList.get(j));
}else if(i == 2) {
dayOfWeekMap.put("dayOfWeek"+ dateList.get(j), electricList.get(j));
}
else {
dayOfWeekMap.put("dayOfWeek"+ dateList.get(j), 0);
}
dayOfWeekList.add(dayOfWeekMap);
valMap.put(dateList.get(j), dayOfWeekList);
}
list.add(valMap);
}
return list;
}3. export :
public void exportMCUOfDay(EnParamsVo vo, HttpServletResponse response){
List<ExcelExportEntity> colList = getHeadList(vo);
List<String> idList = eStruService.getNodeListByDeptIdAndLevel(vo.getSelCode(), "3");
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
if (CollectionUtils.isEmpty(idList)) {
return;
}
idList.forEach(r->{
vo.setSelCode(r);
String name = eStruService.getOne(new QueryWrapper<EnergyStructure>().eq("id", r)).getName();
QueryWrapper<EnergyStructure> queryWrapper = new QueryWrapper<EnergyStructure>();
if (CollectionUtils.isNotEmpty(idList)) {
queryWrapper.eq("parent_id", r);
} else {
queryWrapper.eq("id", "");
}
queryWrapper.isNotNull("code");
List<String> centerNameList = eStruService.list(queryWrapper).stream().map(x ->x.getCode())
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(centerNameList)) {
centerNameList = Arrays.asList("1");
}
Map<String, Object> map = queryMCUOfDay(vo, centerNameList);
list.addAll(getExcelList(map,name));
});
String sheetName = " Power consumption details ";
ExportParams exportParams = new ExportParams();
exportParams.setSheetName(sheetName);
exportParams.setStyle(ExcelExportStylerImpl.class);
exportParams.setCreateHeadRows(true);
exportParams.setHeaderHeight(500D);
try {
ExcelUtils.exportExcel(exportParams, colList,list, response);
} catch (Exception e) {
e.printStackTrace();
}
}Exhibition :

边栏推荐
- Question note 4 (the first wrong version, search the insertion position)
- 我该如何理解工艺
- 关于 CMS 垃圾回收器,你真的懂了吗?
- Oracle system composition
- 大学生参加六星教育PHP培训,找到了薪水远超同龄人的工作
- 给定正整数N、M,均介于1~10 ^ 9之间,N <= M,找出两者之间(含N、M)的位数为偶数的数有多少个
- 【深度学习】:《PyTorch入门到项目实战》第二天:从零实现线性回归(含详细代码)
- Question making note 3 (two point search)
- 华为Mate 40系列曝光:大曲率双曲面屏,5nm麒麟1020处理器!还将有天玑1000+的版本
- 【深度学习】:《PyTorch入门到项目实战》第五天:从0到1实现Softmax回归(含源码)
猜你喜欢

Cluster construction and use of redis5

Applet: scroll view slides to the bottom by default

Brother Ali teaches you how to correctly understand the problem of standard IO buffer

Leetcode learn to insert and sort unordered linked lists (detailed explanation)

综合设计一个OPPE主页--页面的售后服务

Interesting kotlin 0x08:what am I

概率论与数理统计第一章

【深度学习】:《PyTorch入门到项目实战》第六天:多层感知机(含代码)

【深度学习】:《PyTorch入门到项目实战》第一天:数据操作和自动求导

小程序:scroll-view默认滑倒最下面
随机推荐
如何使用Fail2Ban保护WordPress登录页面
Alibaba cloud - Wulin headlines - site building expert competition
Jsonarray traversal
SUSE Ceph 增加节点、减少节点、 删除OSD磁盘等操作 – Storage6
Leetcode learn to insert and sort unordered linked lists (detailed explanation)
【深度学习】:《PyTorch入门到项目实战》第七天之模型评估和选择(上):欠拟合和过拟合(含源码)
给定正整数N、M,均介于1~10 ^ 9之间,N <= M,找出两者之间(含N、M)的位数为偶数的数有多少个
NoSQL introduction practice notes I
技术分享 | 误删表以及表中数据,该如何恢复?
【深度学习】:《PyTorch入门到项目实战》第九天:Dropout实现(含源码)
Mysql与Oracle的13点区别
Interesting kotlin 0x0a:fun with composition
Cluster construction and use of redis5
在AD中添加差分对及连线
Introduction and implementation of stack (detailed explanation)
[deep learning]: model evaluation and selection on the seventh day of pytorch introduction to project practice (Part 1): under fitting and over fitting (including source code)
In 2020q2, shipments in the global tablet market soared by 26.1%: Huawei ranked third and Lenovo increased the most!
Leetcode learn complex questions with random pointer linked lists (detailed explanation)
Re14:读论文 ILLSI Interpretable Low-Resource Legal Decision Making
A total of 13billion flash and 400million MCU were shipped! In depth analysis of the three product lines of Zhaoyi innovation