浙江省网站建设_网站建设公司_C#_seo优化
2025/12/24 9:33:24 网站建设 项目流程

1、导入依赖

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>4.0.3</version>
</dependency>
2、Controller层需要写的代码如下

@PostMapping("/exportAssetsExcel")
public void exportAssetsExcel(@RequestBody SearchCriteria searchCriteria, HttpServletResponse response) throws IOException {
// 查询数据逻辑
List list = new ArrayList<>();

// 设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 中文文件名处理
String fileName = URLEncoder.encode("文件名", "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//设置头居中
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//设置内容
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//设置居中
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
contentWriteCellStyle.setWrapped(false); // 防止换行影响对齐(重要!)
//内容策略
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
// 使用 EasyExcel 直接写入响应流
try (ServletOutputStream out = response.getOutputStream()) {
EasyExcel.write(out, EquipmentAssetsInfo.class)
.registerWriteHandler(horizontalCellStyleStrategy) // ✅ 注册样式策略
.sheet("sheet名称")
.doWrite(list); // 直接传要导出的数据list
} catch (Exception e) {
// 出错时返回错误信息
response.reset();
response.setContentType("application/json");
response.getWriter().write("{\"code\":500,\"message\":\"导出失败: " + e.getMessage() + "\"}");
}
}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询