Java 使用 EasyExcel 实现 Excel 文件读写

EasyExcel 是阿里巴巴开源的一个用于读写 Excel 文件的 Java 库,它提供简单易用的 API,能够高效地处理大数据量的 Excel 文件。

导出 Excel 文件

public static <T> void write(HttpServletResponse response, String filename, Class<T> head, List<T> data) throws IOException {
    response.setContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    response.setCharacterEncoding('utf-8');
    String fileName = URLEncoder.encode(filename, 'UTF-8').replaceAll('\+', '%20');
    response.setHeader('Content-disposition', 'attachment;filename*=utf-8''' + fileName + '.xlsx');
    EasyExcel.write(response.getOutputStream(), head).sheet('sheel1').doWrite(data);
}

代码解析:

  1. 设置响应头信息,指定文件类型为 Excel 文件,字符编码为 UTF-8。
  2. 使用 URLEncoder 对文件名进行编码,防止文件名包含特殊字符导致错误。
  3. 设置响应头 Content-disposition,指定文件下载时的文件名。
  4. 使用 EasyExcel 的 write() 方法将数据写入到 Excel 文件中,并指定工作表名称为 'sheel1'。

读取 Excel 文件

public static <T> List<T> read(InputStream inputStream, Class<T> head) throws IOException {
    return EasyExcel.read(inputStream).head(head).sheet().doReadSync();
}

代码解析:

  1. 使用 EasyExcel 的 read() 方法读取 Excel 文件。
  2. 指定 Excel 文件的头部信息类型为 head
  3. 使用 sheet() 方法选择要读取的工作表,默认读取第一个工作表。
  4. 使用 doReadSync() 方法同步读取 Excel 文件数据,并返回一个 List 类型的数据集合。

总结

EasyExcel 提供了简单易用的 API,可以轻松实现 Excel 文件的读写操作,对于处理大数据量的 Excel 文件非常有效。

注意:

  • 需要在项目中添加 EasyExcel 依赖库。
  • 可以根据实际需求修改代码中的参数,例如工作表名称、文件名等。

原文地址: https://www.cveoy.top/t/topic/piBu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录