这是一个easyexcel模板导出:​​https://gitee.com/xiao-hao123/easyexcel-demo.git​

下面这个使用的时候注意模板要用 xls,也可以用xlsx,如果有问题改成xls,仅仅针对模板格式

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created on 2022/12/30.
*
* @author lichuanming
*/

@Slf4j
@Service
public class EasyExcelService {


public static final String SUFFIX_2007 = ".xlsx";


private static final String CONTENT_DISPOSITION = "Content-disposition";
private static final String ATTACHMENT_FILENAME = "attachment;filename*=utf-8''";
private static final String COM_MSG = "导出文件异常——》";


/**
* exce导出,异常时会导出异常文件
*
* @param response
* @param datas 数据
* @param classz 实体类
* @param excelName excel名称
* @param writeHandler 自定义拦截器
* @param <T>
*/
public <T> void writeWebErrorByTemplate(HttpServletResponse response, List<T> datas, Class<T> classz, String excelName,
WriteHandler writeHandler, String templateName, String title, String title2, String date) {

if (StringUtils.endsWith(excelName, SUFFIX_2007)) {
excelName = excelName.replace(SUFFIX_2007, "");
}

// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
try {
OutputStream outputStream = response.getOutputStream();
// 字符串替换 符号‘\’
String fileName = URLEncoder.encode(excelName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + fileName + SUFFIX_2007);

ClassPathResource classPathResource = new ClassPathResource("/template/bywsReportForm.xls");
String templatePath = classPathResource.getFile().getPath();


ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templatePath).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(datas, fillConfig, writeSheet);
Map<String, Object> map = new HashMap<>();
map.put("title", title != null ? title : null);
map.put("title2", title2 != null ? title2 : null);
map.put("date", date != null ? date : null);
excelWriter.fill(map, writeSheet);
excelWriter.finish();

} catch (IOException e) {
// 导出异常文件
log.error(COM_MSG, e);
}
}


}

不恋尘世浮华,不写红尘纷扰