使用 com.alibaba.easyexcel 读取上传的Excel文件:
1、添加maven依赖
<!-- Excel转换 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.2.1</version>
</dependency>
2、读取上传的excel文件
/**
* 将excel转成列表
*
* @param file 文件
* @param head Class
* @param <T> 泛型对象
* @return 对象列表
* @throws IOException 读取失败的情况
*/
public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
return EasyExcel.read(file.getInputStream(), head, null)
.autoCloseStream(false)
.doReadAllSync();
}
3、写出excel文件
/** * 将列表以 Excel 响应给前端 * * @param response 响应 * @param filename 文件名 * @param sheetName Excel sheet 名 * @param head Excel head 头 * @param data 数据列表哦 * @param <T> 泛型,保证 head 和 data 类型的一致性 * @throws IOException 写入失败的情况 */ public static <T> void write(HttpServletResponse response, String filename, String sheetName, Class<T> head, List<T> data) throws IOException { EasyExcel.write(response.getOutputStream(), head) .autoCloseStream(false) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) .sheet(sheetName).doWrite(data); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); }
4、使用模板
/** * 将数据按照模板填充,并以 Excel 响应给前端 * * @param response 响应 * @param fileName 文件名 * @param sheetName Excel sheet 名 * @param templateFileName 模板 * @param data 数据 * @throws IOException 写入失败的情况 */ public static <T> void writeForTemplate(HttpServletResponse response, String fileName, String sheetName, String templateFileName, Map<String,Object> data) throws IOException { EasyExcel.write(response.getOutputStream()) .withTemplate(templateFileName) .sheet(sheetName).doFill(data); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); }
朝菌不知晦朔,蟪蛄不知春秋
浙公网安备 33010602011771号