package com.alpha.erp.util.easyExcel; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.support.ExcelTypeEnum; import com.orderplus.core.handle.BusinessException; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; import java.util.List; /** * @program: alpha-bi-system * @description: easyExcel工具类 * @author: xianjie.Ye * @create: 2022-07-29 */ @Component public class EasyExcelUtils { //读取excel数据 public <T> List<T> read(MultipartFile file, Class<T> clazz, Integer headRowNum) { try { EasyExcelReadListener<T> listener = new EasyExcelReadListener<>(); EasyExcel.read(file.getInputStream(), clazz, listener).sheet().headRowNumber(headRowNum).doRead(); return listener.getRows(); } catch (IOException e) { throw new BusinessException(600, "读取excel数据失败!" + e.getMessage(), null); } } //读取excel数据 public <T> List<T> read(MultipartFile file, Class<T> clazz, Integer headRowNum, String sheet) { try { EasyExcelReadListener<T> listener = new EasyExcelReadListener<>(); EasyExcel.read(file.getInputStream(), clazz, listener).sheet(sheet).headRowNumber(headRowNum).doRead(); return listener.getRows(); } catch (IOException e) { throw new BusinessException(600, "读取excel数据失败!" + e.getMessage(), null); } } public static <T> void writeExcel(List<T> list, Class<T> clazz, HttpServletResponse response, String fileName) throws Exception { fileName = URLEncoder.encode(fileName, "UTF-8"); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";filename*=utf-8''" + fileName + ".xlsx"); ServletOutputStream outputStream = response.getOutputStream(); try { EasyExcel.write(outputStream, clazz) .registerWriteHandler(new CellStyleUtils()) .registerWriteHandler(new ExcelCellWidthStyleUtils()) .excelType(ExcelTypeEnum.XLSX) .sheet("sheet").doWrite(list); } catch (Exception e) { throw new RuntimeException(e); }finally { outputStream.flush(); outputStream.close(); } } }
文章来源地址https://www.toymoban.com/news/detail-429162.html
文章来源:https://www.toymoban.com/news/detail-429162.html
到了这里,关于excel导入工具类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!