excel导出(支持多工作表)
maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
相关实例
启动文件
package com.ntt.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class CmsApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(CmsApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CmsApplication.class);
}
}
server:
port: 9999
控制类
package com.ntt.web.controller;
import com.ntt.web.pojo.Student;
import com.ntt.web.utils.ExcelUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;
@RestController
@RequestMapping("/api/v1")
public class StuController {
@GetMapping(value = "/download")
public void download(HttpServletResponse response) throws Exception{
List<Student> list = new ArrayList<>();
list.add(new Student().setName("小白").setAge(10).setCreateTime(LocalDateTime.now()));
list.add(new Student().setName("小黑").setAge(11).setCreateTime(LocalDateTime.now()));
LinkedHashMap<String, List<?>> resultMap = new LinkedHashMap<>();
resultMap.put("结果", list);
ExcelUtils.dataType = Arrays.asList(new Student());
ExcelUtils.httpSaveByExcel(response, resultMap);
}
}
实体类
package com.ntt.web.pojo;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public class Student {
private static final long serialVersionUID = 1L;
@ExcelProperty(value = "姓名")
private String name;
@ExcelProperty(value = "年龄")
private Integer age;
@ExcelIgnore
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
}
工具类
package com.ntt.web.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelUtils {
public static List<?> dataType = null;
public static void httpSaveByExcel(HttpServletResponse response, LinkedHashMap<String,List<?>> resultMap) throws Exception {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
try{
SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
String fileName = URLEncoder.encode(dft.format(new Date()), "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
Integer sheetNum = 0;
if (resultMap != null && !resultMap.isEmpty()){
for(Map.Entry<String, List<?>> entry : resultMap.entrySet()){
String rmKey = entry.getKey();
List<?> resultVal = entry.getValue();
if (rmKey != null){
resultVal = (resultVal != null && !resultVal.isEmpty()) ? resultVal : new ArrayList<>();
excelWriter.write(
resultVal,
EasyExcel.writerSheet(sheetNum, rmKey)
.head(dataType.get(sheetNum).getClass())
.registerWriteHandler(myHorizontalCellStyleStrategy())
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.build()
);
sheetNum ++;
}
}
}
excelWriter.finish();
}catch (Exception e){
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().println(e);
}
}
public static void localSaveByExcel(LinkedHashMap<String,List<?>> resultMap, String resultPath) throws IOException {
File outFile = new File(resultPath);
OutputStream outputStream = null;
ExcelWriter excelWriter = null;
try{
outputStream = new FileOutputStream(resultPath);
if (!outFile.exists()){
File parentFile = outFile.getParentFile();
if (!parentFile.exists()){
parentFile.mkdirs();
}
outFile.createNewFile();
}
excelWriter = EasyExcel.write(outputStream).build();
Integer sheetNum = 0;
if (resultMap != null && !resultMap.isEmpty()){
for(Map.Entry<String, List<?>> entry : resultMap.entrySet()){
String rmKey = entry.getKey();
List<?> resultVal = entry.getValue();
if (rmKey != null){
resultVal = (resultVal != null && !resultVal.isEmpty()) ? resultVal : new ArrayList<>();
excelWriter.write(
resultVal,
EasyExcel.writerSheet(sheetNum, rmKey)
.head(dataType.get(sheetNum).getClass())
.registerWriteHandler(myHorizontalCellStyleStrategy())
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.build()
);
sheetNum ++;
}
}
}
}catch (Exception e){
e.printStackTrace();
}
finally {
if (excelWriter != null) {
excelWriter.finish();
}
if (outputStream != null){
outputStream.close();
}
}
}
public static HorizontalCellStyleStrategy myHorizontalCellStyleStrategy(){
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontName("等线");
headWriteFont.setFontHeightInPoints((short)11);
headWriteCellStyle.setWriteFont(headWriteFont);
List<WriteCellStyle> listCntWritCellSty = new ArrayList<>();
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
WriteFont contentWriteFont = new WriteFont();
contentWriteFont.setFontName("宋体");
contentWriteFont.setFontHeightInPoints((short)11);
contentWriteCellStyle.setWriteFont(contentWriteFont);
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
contentWriteCellStyle.setWrapped(false);
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
setBorderStyle(contentWriteCellStyle);
listCntWritCellSty.add(contentWriteCellStyle);
return new HorizontalCellStyleStrategy(headWriteCellStyle, listCntWritCellSty);
}
private static void setBorderStyle(WriteCellStyle contentWriteCellStyle){
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
}
}


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix