import com.alibaba.excel.EasyExcel; import com.alibaba.excel.read.listener.ReadListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.ss.formula.functions.T; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; /** * 基于EasyExcel的导入导出工具类, 在使用时需要先将excel实体类中的字段使用@ExcelProperty来指定表头 * {@link com.alibaba.excel.annotation.ExcelProperty} * {@link com.alibaba.excel.annotation.write.style.ColumnWidth} * {@link com.alibaba.excel.annotation.format.DateTimeFormat} */ public class EasyExcelAlibabaUtil { private static Log logger = LogFactory.getLog("EasyExcelAlibabaUtil"); /** * 将excel文件转化成javaList集合, * 需要在传入的class的字段中加入EasyExcel的专用注解来指定表名 * @param excelFile * @param clazz * @param <T> * @return */ public static <T> List<T> excelToList(MultipartFile excelFile, Class<T> clazz) { List<T> objects = null; try { InputStream inputStream = excelFile.getInputStream(); objects = EasyExcel.read(inputStream).head(clazz).sheet().doReadSync(); } catch (Exception e) { logger.error("excelToList-exception", e); } finally { return objects; } } /** * 读取excel,这个相当于一个高性能模式。 * 比上面的方法多了一个readListener接口, 需要传一个实现这个接口的实现类 * 其中invoke方法是每读取一行都会调用, 所以可以读取一行处理一行, 性能比较高。 * @param excelFile * @param clazz * @param readListener */ public static void readExcelHighSpeed(MultipartFile excelFile, Class<T> clazz, ReadListener readListener) { try { InputStream inputStream = excelFile.getInputStream(); EasyExcel.read(inputStream, clazz, readListener).sheet().doRead(); } catch (Exception e) { logger.error("excelToList-readExcelHighSpeed", e); } } /** * 下载excel * @param response * @param clazz * @param list * @param excelName */ public static void download(HttpServletResponse response, Class<?> clazz, List<?> list, String excelName) { try { ServletOutputStream outputStream = response.getOutputStream(); response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); EasyExcel.write(baos, clazz).sheet("sheet1").doWrite(list); response.setHeader("Content-Length", String.valueOf(baos.size())); outputStream.write(baos.toByteArray()); response.flushBuffer(); } catch(Exception e){ logger.error("excelToList-download", e); } } }