1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| package org.geekboy.common;
import cn.hutool.core.convert.Convert; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.write.metadata.WriteSheet;
import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List;
public class ExcelUtil {
public static <T> List<T> readExcel(InputStream excelInputStream, String fileName,Class<T> clazz) { ExcelListener excelListener = new ExcelListener(); ExcelReader excelReader = getReader(excelInputStream, fileName,clazz, excelListener); if (excelReader == null) { return new ArrayList<>(); } List<ReadSheet> readSheetList = excelReader.excelExecutor().sheetList(); for (ReadSheet readSheet : readSheetList) { excelReader.read(readSheet); } excelReader.finish(); return Convert.toList(clazz, excelListener.getDataList()); }
public static <T> void writeExcel(HttpServletResponse response, List<T> list, String fileName, String sheetName, Class<T> clazz) {
OutputStream outputStream = getOutputStream(response, fileName); ExcelWriter excelWriter = EasyExcel.write(outputStream, clazz).build(); WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build(); excelWriter.write(list, writeSheet); excelWriter.finish(); }
private static OutputStream getOutputStream(HttpServletResponse response, String fileName) { String filePath = fileName + ".xlsx"; File file = new File(filePath); try { if (!file.exists() || file.isDirectory()) { file.createNewFile(); } fileName = new String(filePath.getBytes(), "ISO-8859-1"); response.addHeader("Content-Disposition", "filename=" + fileName); return response.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } return null; }
private static <T> ExcelReader getReader(InputStream inputStream, String filename, Class<T> clazz, ExcelListener excelListener) { try { if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) { return null; } ExcelReader excelReader = EasyExcel.read(inputStream, clazz, excelListener).build(); inputStream.close(); return excelReader; } catch (Exception e) { e.printStackTrace(); } return null; } }
|