最新的依赖见: https://mvnrepository.com/artifact/com.alibaba/easyexcel
public class EasyExcelUtil {
/**
* Excel文件导出
* @param response
* @param fileName:导出Excel文件名称
* @param sheetName:Excel的Sheet名称
* @param headList:Excel标题名称
* @param bodyList:Excel内容
* @throws Exception
*/
public static void writeExcel(HttpServletResponse response, String fileName, String sheetName,
List> headList, List> bodyList) throws Exception {
if (null == fileName) {
throw new Exception("文件名称不能为空!");
}
if (null == sheetName) {
throw new Exception("Excel的Sheet名称不能为空!");
}
if (null == headList) {
throw new Exception("文件标题不能为空!");
}
ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
Sheet sheet1 = new Sheet(1, 1);
sheet1.setSheetName(sheetName);
sheet1.setTableStyle(createDefaultTableStyle());
sheet1.setHead(headList);
// 设置自适应宽度
sheet1.setAutoWidth(Boolean.TRUE);
if (null != bodyList) {
writer.write1(bodyList, sheet1);
}
writer.finish();
}
/**
* 导出文件名称定义
*
* @param fileName:文件名称
* @param response
* HttpServletResponse
* @return
* @throws Exception
*/
public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
return response.getOutputStream();
} catch (IOException e) {
throw new Exception("导出excel表格失败!", e);
}
}
/**
* 设置默认的导出样式
*
* @return
*/
public static TableStyle createDefaultTableStyle() {
TableStyle tableStyle = new TableStyle();
Font headFont = new Font();
headFont.setBold(true);
headFont.setFontHeightInPoints((short) 12);
headFont.setFontName("微软雅黑");
tableStyle.setTableHeadFont(headFont);
tableStyle.setTableHeadBackGroundColor(IndexedColors.WHITE);
Font contentFont = new Font();
contentFont.setBold(false);
contentFont.setFontHeightInPoints((short) 11);
contentFont.setFontName("微软雅黑");
tableStyle.setTableContentFont(contentFont);
tableStyle.setTableContentBackGroundColor(IndexedColors.WHITE);
return tableStyle;
}
}
@RequestMapping(value="/exportexcel", method = RequestMethod.GET)
public void exportexcel(HttpServletRequest request,
HttpServletResponse response) throws Exception{
EasyExcelUtil.writeExcel(response, "easy文件名称", "sheet名称",
DataUtil.createTestListStringHead2(),
DataUtil.createTestListObject());
}
public class DataUtil {
public static List> createTestListObject() {
List> object = new ArrayList>();
for (int i = 0; i < 300000; i++) {
List
}
https://github.com/alibaba/easyexcel
https://www.cnblogs.com/kaile/p/10869453.html
https://blog.csdn.net/qq_35206261/article/details/82844159