EasyExcel实现导入excel

客官°小女子只卖身不卖艺 2022-01-15 22:23 433阅读 0赞

1.pom.xml配置依赖包

  1. <!-- xls格式excel依赖包 -->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.17</version>
  6. </dependency>
  7. <!--xlsx格式excel依赖包-->
  8. <dependency>
  9. <groupId>org.apache.poi</groupId>
  10. <artifactId>poi-ooxml</artifactId>
  11. <version>3.17</version>
  12. </dependency>
  13. <!-- easyexcel依赖包 -->
  14. <dependency>
  15. <groupId>com.alibaba</groupId>
  16. <artifactId>easyexcel</artifactId>
  17. <version>1.1.2-beta5</version>
  18. </dependency>

2.编写excel导入对应实体类

  1. import com.alibaba.excel.annotation.ExcelProperty;
  2. import com.alibaba.excel.metadata.BaseRowModel;
  3. public class TestModel extends BaseRowModel {
  4. @ExcelProperty(value = "姓名", index = 0)
  5. private String xm;
  6. @ExcelProperty(value = "微信号", index = 1)
  7. private String wxh;
  8. @ExcelProperty(value = "手机号", index = 2)
  9. private String sjh;
  10. public String getXm() {
  11. return xm;
  12. }
  13. public void setXm(String xm) {
  14. this.xm = xm;
  15. }
  16. public String getWxh() {
  17. return wxh;
  18. }
  19. public void setWxh(String wxh) {
  20. this.wxh = wxh;
  21. }
  22. public String getSjh() {
  23. return sjh;
  24. }
  25. public void setSjh(String sjh) {
  26. this.sjh = sjh;
  27. }
  28. }

3.编写导入监听类

  1. import java.lang.reflect.Field;
  2. import java.util.ArrayList;
  3. import java.util.LinkedHashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import com.alibaba.excel.context.AnalysisContext;
  7. import com.alibaba.excel.event.AnalysisEventListener;
  8. import com.alibaba.excel.metadata.ExcelHeadProperty;
  9. public class ExcelListener extends AnalysisEventListener {
  10. //自定义用于暂时存储data
  11. private List<Object> datas = new ArrayList<>();
  12. //导入表头
  13. private String importHeads = "";
  14. //模版表头
  15. private String modelHeads = "";
  16. /**
  17. * 通过 AnalysisContext 对象还可以获取当前 sheet,当前行等数据
  18. */
  19. @Override
  20. public void invoke(Object o, AnalysisContext analysisContext) {
  21. Integer currentRowNum = analysisContext.getCurrentRowNum();
  22. //获取导入表头,默认第一行为表头
  23. if(currentRowNum == 0){
  24. try {
  25. Map<String,Object> m = objToMap(o);
  26. for (Object v : m.values()) {
  27. importHeads += String.valueOf(v).trim() + ",";
  28. }
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }else{
  33. datas.add(o);
  34. }
  35. }
  36. /**
  37. * 读取完之后的操作
  38. */
  39. @Override
  40. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  41. //获取模版表头
  42. ExcelHeadProperty ehp = analysisContext.getExcelHeadProperty();
  43. for(List<String> s : ehp.getHead()){
  44. modelHeads += s.get(0) + ",";
  45. }
  46. }
  47. public List<Object> getDatas() {
  48. return datas;
  49. }
  50. public void setDatas(List<Object> datas) {
  51. this.datas = datas;
  52. }
  53. public String getImportHeads() {
  54. return importHeads;
  55. }
  56. public void setImportHeads(String importHeads) {
  57. this.importHeads = importHeads;
  58. }
  59. public String getModelHeads() {
  60. return modelHeads;
  61. }
  62. public void setModelHeads(String modelHeads) {
  63. this.modelHeads = modelHeads;
  64. }
  65. //Object转换为Map
  66. public Map<String,Object> objToMap(Object obj) throws Exception{
  67. Map<String,Object> map = new LinkedHashMap<String, Object>();
  68. Field[] fields = obj.getClass().getDeclaredFields();
  69. for(Field field : fields){
  70. field.setAccessible(true);
  71. map.put(field.getName(), field.get(obj));
  72. }
  73. return map;
  74. }
  75. }

4.编写导入工具类

  1. import java.io.BufferedInputStream;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.List;
  5. import org.springframework.web.multipart.MultipartFile;
  6. import com.alibaba.excel.ExcelReader;
  7. import com.alibaba.excel.metadata.BaseRowModel;
  8. import com.alibaba.excel.metadata.Sheet;
  9. public class EasyExcelUtil {
  10. /**
  11. * 读取某个 sheet 的 Excel
  12. *
  13. * @param excel 文件
  14. * @param rowModel 实体类映射,继承 BaseRowModel 类
  15. * @param sheetNo sheet 的序号 从1开始
  16. * @return Excel 数据 list
  17. */
  18. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel) throws IOException {
  19. return readExcel(excel, rowModel, 1, 1);
  20. }
  21. /**
  22. * 读取某个 sheet 的 Excel
  23. * @param excel 文件
  24. * @param rowModel 实体类映射,继承 BaseRowModel 类
  25. * @param sheetNo sheet 的序号 从1开始
  26. * @return Excel 数据 list
  27. */
  28. public static Map<String,Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) throws IOException {
  29. Map<String,Object> result = new HashMap<>();
  30. ExcelListener excelListener = new ExcelListener();
  31. ExcelReader reader = getReader(excel, excelListener);
  32. if (reader == null) {
  33. return null;
  34. }
  35. reader.read(new Sheet(sheetNo, 0, rowModel.getClass()));
  36. //校验表头
  37. Boolean flag = false;
  38. if(excelListener.getImportHeads().equals(excelListener.getModelHeads())){
  39. flag = true;
  40. }
  41. result.put("flag", flag);
  42. result.put("datas", excelListener.getDatas());
  43. return result;
  44. }
  45. /**
  46. * 读取某个 sheet 的 Excel
  47. * @param excel 文件
  48. * @param rowModel 实体类映射,继承 BaseRowModel 类
  49. * @param sheetNo sheet 的序号 从1开始
  50. * @param headLineNum 表头行数,默认为1
  51. * @return Excel 数据 list
  52. */
  53. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo, int headLineNum) throws IOException {
  54. ExcelListener excelListener = new ExcelListener();
  55. ExcelReader reader = getReader(excel, excelListener);
  56. if (reader == null) {
  57. return null;
  58. }
  59. reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));
  60. return excelListener.getDatas();
  61. }
  62. /**
  63. * 读取指定sheetName的Excel(多个 sheet)
  64. * @param excel 文件
  65. * @param rowModel 实体类映射,继承 BaseRowModel 类
  66. * @return Excel 数据 list
  67. * @throws IOException
  68. */
  69. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel,String sheetName) throws IOException {
  70. ExcelListener excelListener = new ExcelListener();
  71. ExcelReader reader = getReader(excel, excelListener);
  72. if (reader == null) {
  73. return null;
  74. }
  75. for (Sheet sheet : reader.getSheets()) {
  76. if (rowModel != null) {
  77. sheet.setClazz(rowModel.getClass());
  78. }
  79. //读取指定名称的sheet
  80. if(sheet.getSheetName().contains(sheetName)){
  81. reader.read(sheet);
  82. break;
  83. }
  84. }
  85. return excelListener.getDatas();
  86. }
  87. /**
  88. * 返回 ExcelReader
  89. * @param excel 需要解析的 Excel 文件
  90. * @param excelListener new ExcelListener()
  91. * @throws IOException
  92. */
  93. private static ExcelReader getReader(MultipartFile excel,ExcelListener excelListener) throws IOException {
  94. String filename = excel.getOriginalFilename();
  95. if(filename != null && (filename.toLowerCase().endsWith(".xls") || filename.toLowerCase().endsWith(".xlsx"))){
  96. InputStream is = new BufferedInputStream(excel.getInputStream());
  97. return new ExcelReader(is, null, excelListener, false);
  98. }else{
  99. return null;
  100. }
  101. }
  102. }

5.业务层调用

  1. //导入excel
  2. @RequestMapping(value = "excelImport", method = {RequestMethod.GET, RequestMethod.POST })
  3. public String excelImport(HttpServletRequest request,Model model,@RequestParam("uploadFile") MultipartFile[] files) throws Exception {
  4. if(files != null && files.length > 0){
  5. MultipartFile file = files[0];
  6. Map<String,Object> result = EasyExcelUtil.readExcel(file, new TestModel(),1);
  7. Boolean flag = (Boolean) result.get("flag");
  8. if(flag){
  9. List<Object> list = (List<Object>) result.get("datas");
  10. if(list != null && list.size() > 0){
  11. for(Object o : list){
  12. TestModel xfxx = (TestModel) o;
  13. System.out.println(xfxx.getXm()+"/"+xfxx.getSjh()+"/"+xfxx.getSjh());
  14. }
  15. }
  16. }else{
  17. System.out.println("表头格式错误");
  18. }
  19. }
  20. return "index";
  21. }

发表评论

表情:
评论列表 (有 0 条评论,433人围观)

还没有评论,来说两句吧...

相关阅读