MCPcopy Create free account
hub / github.com/Bit0r/java-util / EasyExcelUtil

Class EasyExcelUtil

src/main/java/util/EasyExcelUtil.java:21–75  ·  view source on GitHub ↗

excel工具类 easyexcel使用的3.0.2版本,跟以前版本有很大区别,且不兼容1.x版本

Source from the content-addressed store, hash-verified

19 * easyexcel使用的3.0.2版本,跟以前版本有很大区别,且不兼容1.x版本
20 */
21public class EasyExcelUtil {
22 private static final Logger LOGGER = LoggerFactory.getLogger(EasyExcelUtil.class);
23
24 public static <T> List<T> read(String filePath, final Class<?> clazz) {
25 File f = new File(filePath);
26 try (FileInputStream fis = new FileInputStream(f)) {
27 return read(fis, clazz);
28 } catch (FileNotFoundException e) {
29 LOGGER.error("文件{}不存在", filePath, e);
30 } catch (IOException e) {
31 LOGGER.error("文件读取出错", e);
32 }
33 return null;
34 }
35
36 public static <T> List<T> read(InputStream inputStream, final Class<?> clazz) {
37 if (inputStream == null) {
38 LOGGER.error("解析出错了,文件流是null");
39 }
40 // 有个很重要的点 DataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
41 DataListener<T> listener = new DataListener<>();
42 // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
43 EasyExcel.read(inputStream, clazz, listener).sheet().doRead();
44 return listener.getRows();
45 }
46
47 public static void write(String outFile, List<?> list) {
48 Class<?> clazz = list.get(0).getClass();
49 EasyExcel.write(outFile, clazz).sheet().doWrite(list);
50 }
51
52 public static void write(String outFile, List<?> list, String sheetName) {
53 Class<?> clazz = list.get(0).getClass();
54 EasyExcel.write(outFile, clazz).sheet(sheetName).doWrite(list);
55 }
56
57 public static void write(OutputStream outputStream, List<?> list, String sheetName) {
58 Class<?> clazz = list.get(0).getClass();
59 // sheetName为sheet的名字,默认写第一个sheet
60 EasyExcel.write(outputStream, clazz).sheet(sheetName).doWrite(list);
61 }
62
63 /**
64 * 文件下载(失败了会返回一个有部分数据的Excel),用于直接把excel返回到浏览器下载
65 */
66 public static void download(HttpServletResponse response, List<?> list, String sheetName) throws IOException {
67 Class<?> clazz = list.get(0).getClass();
68 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
69 response.setCharacterEncoding("utf-8");
70 // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
71 String fileName = URLEncoder.encode(sheetName, "UTF-8").replaceAll("\\+", "%20");
72 response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
73 EasyExcel.write(response.getOutputStream(), clazz).head(clazz).sheet(sheetName).doWrite(list);
74 }
75}
76
77class DataListener<T> extends AnalysisEventListener<T> {
78

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected