EasyExcel 是一个基于 Java 的开源库,旨在以低内存消耗的方式读写 Excel 文件,支持处理大型文件。其 GitHub 仓库位于 https://github.com/alibaba/easyexcel。以下示例展示了如何实现通过浏览器下载 Excel 文件的功能。
1.在 Maven 项目的 pom.xml
文件中添加 EasyExcel 的依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.0</version>
</dependency>
2. 创建实体类并添加注解(导出)
创建一个实体类 Person
,并使用 @ExcelProperty
和 @ExcelIgnore
注解:
@Setter
@Getter
@ToString
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "Person", autoResultMap = true)
public class Person extends Model<PERSON> {
@TableId(type = IdType.ASSIGN_ID)
@ExcelIgnore
private String Id ;
@ExcelProperty(value = "文件编号",index = 2)
private String code ;
@ExcelProperty(value = "申请类型",index = 0)
private String businessType ;
/** 项目名称 */
@ExcelProperty(value = "项目名称",index = 4)
private String prjName ;
/** 项目id */
@ExcelIgnore
private String prjId ;
}
@ExcelProperty
注解:- 用于指定字段在 Excel 中的列标题。
@ExcelIgnore
注解:- 用于忽略某个字段,使其不参与 Excel 的读写操作。
3.编写工具类
创建一个工具类 ExcelExportUtil
,用于导出 Excel 文件到 HTTP 响应:
/**
* 导出Excel文件到HTTP响应
*
* @param response HTTP响应对象
* @param fileNamePrefix 文件名前缀,将用于生成完整的文件名
* @param dataList 要导出的数据列表
* @param dataClass 数据列表中的元素类型,用于EasyExcel识别
* @throws IOException 如果写入响应时发生错误
*/
public static void exportExcel(HttpServletResponse response, String fileNamePrefix, List<?> dataList, Class<?> dataClass) throws IOException {
// 设置响应内容类型
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 对文件名进行URL编码并添加.xlsx后缀
String fileName = URLEncoder.encode(fileNamePrefix, "UTF-8") + ".xlsx";
// 设置响应头,以附件形式发送
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
// 使用EasyExcel写入数据到响应的输出流
try (OutputStream out = response.getOutputStream()) {
EasyExcel.write(out, dataClass)
.sheet(fileNamePrefix) // 使用文件名前缀作为工作表名
.doWrite(dataList);
} catch (IOException e) {
throw new IOException("Error writing Excel file to response", e);
}
}
4.调用
在实际业务逻辑中调用 ExcelExportUtil
类的 exportExcel
方法:
ExcelExportUtil.exportExcel(response,"管理列表",person,Person.class);
5.总结
通过上述步骤,可以使用 EasyExcel 实现 Excel 文件的导入导出功能。具体步骤包括添加依赖、定义实体类、编写工具类以及调用工具类的方法。