当前位置:网站首页>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 :

边栏推荐
- 关于Bug处理的一些看法
- 【深度学习】:《PyTorch入门到项目实战》第六天:多层感知机(含代码)
- Question note 4 (the first wrong version, search the insertion position)
- 记录ceph两个rbd删除不了的处理过程
- Applet: scroll view slides to the bottom by default
- 【深度学习】:《PyTorch入门到项目实战》第九天:Dropout实现(含源码)
- How to set ticdc synchronization data to only synchronize the specified library?
- Semtech launched Lora edge, a geolocation solution for the Internet of things, and the first chip lr1110 is now on the market
- Re14:读论文 ILLSI Interpretable Low-Resource Legal Decision Making
- 我该如何理解工艺
猜你喜欢

技术分享 | 误删表以及表中数据,该如何恢复?

【深度学习】:《PyTorch入门到项目实战》第四天:从0到1实现logistic回归(附源码)

Probability theory and mathematical statistics Chapter 1

Do you really understand CMS garbage collector?

在AD中添加差分对及连线

阿里云 MSE 支持 Go 语言流量防护

TCP handshake, waving, time wait connection reset and other records

Applet: get element node information

MySQL安装教程

Cluster construction and use of redis5
随机推荐
After paying $1.8 billion in royalties to Qualcomm, Huawei reportedly ordered 120million chips from MediaTek! Official response
Summary of kubenertes 1.16 cluster deployment problems
记录ceph两个rbd删除不了的处理过程
SUSE CEPH add nodes, reduce nodes, delete OSD disks and other operations – storage6
Record the processing process of CEPH two RBDS that cannot be deleted
累计出货130亿颗Flash,4亿颗MCU!深度解析兆易创新的三大产品线
【深度学习】:《PyTorch入门到项目实战》第八天:权重衰退(含源码)
Rsync 服务部署与参数详解
parseJson
[deep learning]: day 1 of pytorch introduction to project practice: data operation and automatic derivation
WSL+Valgrind+Clion
Add differential pairs and connections in Ad
kubenertes 1.16集群部署问题总结
有趣的 Kotlin 0x07:Composition
First day of QT study
Go language slow entry - process control statement
Record development issues
Installation of QT learning
2019年全球移动通信基站市场:爱立信、华为、诺基亚分列前三
Re13:读论文 Gender and Racial Stereotype Detection in Legal Opinion Word Embeddings