当前位置:网站首页>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 making note 2 (add two numbers)
- Implementation of paging
- Detailed steps for setting up SUSE storage6 environment – win10 + VMware Workstation
- HTAP是有代价的
- 如何使用Fail2Ban保护WordPress登录页面
- 做题笔记2(两数相加)
- leetcode9. 回文数
- 微软:Edge 浏览器已内置磁盘缓存压缩技术,可节省空间占用且不降低系统性能
- [deep learning]: day 5 of pytorch introduction to project practice: realize softmax regression from 0 to 1 (including source code)
- parseJson
猜你喜欢

Probability theory and mathematical statistics Chapter 1

ERROR: transport library not found: dt_ socket

小程序:获取元素节点信息

Re13:读论文 Gender and Racial Stereotype Detection in Legal Opinion Word Embeddings

Tcp/ip related

阿里大哥教你如何正确认识关于标准IO缓冲区的问题

Re11:读论文 EPM Legal Judgment Prediction via Event Extraction with Constraints

Microsoft: edge browser has built-in disk cache compression technology, which can save space and not reduce system performance

Cluster construction and use of redis5

【深度学习】:《PyTorch入门到项目实战》第五天:从0到1实现Softmax回归(含源码)
随机推荐
Signal and slot mechanism of QT learning
go语言慢速入门——流程控制语句
QT designer for QT learning
Some suggestions on Oracle SQL tuning
Learn to use MySQL explain to execute the plan, and SQL performance tuning is no longer difficult
Question making note 3 (two point search)
向高通支付18亿美元专利费之后,传华为向联发科订购了1.2亿颗芯片!官方回应
海康威视回应'美国禁令'影响:目前所使用的元器件都有备选
Introduction and implementation of stack (detailed explanation)
Some opinions on bug handling
egg(十九):使用egg-redis性能优化,缓存数据提升响应效率
Create a self-organizing / safe / controllable Lora network! Semtech responded for the first time to the impact of the "new regulations of the Ministry of industry and information technology"
智慧园区是未来发展的趋势吗?
有趣的 Kotlin 0x0A:Fun with composition
Call DLL file without source code
Add differential pairs and connections in Ad
[deep learning]: the second day of pytorch introduction to project practice: realize linear regression from zero (including detailed code)
mysql cdc 如果binlog日志文件不全,全量阶段能读到所有数据吗
3D modeling tool Archicad 26 newly released
Summary of kubenertes 1.16 cluster deployment problems