关于java中Excel的导入导出

打印 上一主题 下一主题

主题 880|帖子 880|积分 2640

前言
提示:留意看文字的提醒:
比方:
提示: 就这几个表别搞乱了就行其实很简单
ExcelClassField ------ Excel标题栏工具类–不消管
ExcelExport------导出配置工具类—用于对象表的配置上
ExcelImport----导入配置工具类—用于对象表的配置上
ExcelUtils-----用于接口调用上
 
一、配置pom依靠
  1.         <dependency>
  2.             <groupId>org.apache.httpcomponents</groupId>
  3.             <artifactId>httpmime</artifactId>
  4.             <version>4.5.7</version>
  5.         </dependency>
  6.         
  7.         <dependency>
  8.             <groupId>com.alibaba</groupId>
  9.             <artifactId>fastjson</artifactId>
  10.             <version>1.2.41</version>
  11.         </dependency>
  12.         
  13.         <dependency>
  14.             <groupId>org.apache.poi</groupId>
  15.             <artifactId>poi-ooxml</artifactId>
  16.             <version>3.16</version>
  17.         </dependency>
复制代码
二、搭建utils工具类

1.Excel表头设置表

代码如下(示例):根本上不消动
  1. package com.information.utils;
  2. import java.util.LinkedHashMap;
  3. /** Excel 表头设置
  4. */
  5. public class ExcelClassField {
  6.     /** 字段名称 */
  7.     private String fieldName;
  8.     /** 表头名称 */
  9.     private String name;
  10.     /** 映射关系 */
  11.     private LinkedHashMap<String, String> kvMap;
  12.     /** 示例值 */
  13.     private Object example;
  14.     /** 排序 */
  15.     private int sort;
  16.     /** 是否为注解字段:0-否,1-是 */
  17.     private int hasAnnotation;
  18.     public String getFieldName() {
  19.         return fieldName;
  20.     }
  21.     public void setFieldName(String fieldName) {
  22.         this.fieldName = fieldName;
  23.     }
  24.     public String getName() {
  25.         return name;
  26.     }
  27.     public void setName(String name) {
  28.         this.name = name;
  29.     }
  30.     public LinkedHashMap<String, String> getKvMap() {
  31.         return kvMap;
  32.     }
  33.     public void setKvMap(LinkedHashMap<String, String> kvMap) {
  34.         this.kvMap = kvMap;
  35.     }
  36.     public Object getExample() {
  37.         return example;
  38.     }
  39.     public void setExample(Object example) {
  40.         this.example = example;
  41.     }
  42.     public int getSort() {
  43.         return sort;
  44.     }
  45.     public void setSort(int sort) {
  46.         this.sort = sort;
  47.     }
  48.     public int getHasAnnotation() {
  49.         return hasAnnotation;
  50.     }
  51.     public void setHasAnnotation(int hasAnnotation) {
  52.         this.hasAnnotation = hasAnnotation;
  53.     }
  54. }
复制代码
2.Excel导入导出工具类

代码如下(示例):
  1. package com.information.utils;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import org.apache.poi.hssf.usermodel.HSSFDataValidation;
  5. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  6. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  7. import org.apache.poi.ss.usermodel.*;
  8. import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
  9. import org.apache.poi.ss.util.CellRangeAddress;
  10. import org.apache.poi.ss.util.CellRangeAddressList;
  11. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  12. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
  13. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  14. import org.springframework.web.multipart.MultipartFile;
  15. import javax.servlet.ServletOutputStream;
  16. import javax.servlet.http.HttpServletResponse;
  17. import java.io.*;
  18. import java.lang.reflect.Field;
  19. import java.math.BigDecimal;
  20. import java.math.RoundingMode;
  21. import java.net.URL;
  22. import java.text.NumberFormat;
  23. import java.text.SimpleDateFormat;
  24. import java.util.*;
  25. import java.util.Map.Entry;
  26. import java.util.regex.Pattern;
  27. /**
  28. * Excel导入导出工具类
  29. */
  30. @SuppressWarnings("unused")
  31. public class ExcelUtils {
  32.     private static final String XLSX = ".xlsx";
  33.     private static final String XLS = ".xls";
  34.     public static final String ROW_MERGE = "row_merge";
  35.     public static final String COLUMN_MERGE = "column_merge";
  36.     private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
  37.     private static final String ROW_NUM = "rowNum";
  38.     private static final String ROW_DATA = "rowData";
  39.     private static final String ROW_TIPS = "rowTips";
  40.     private static final int CELL_OTHER = 0;
  41.     private static final int CELL_ROW_MERGE = 1;
  42.     private static final int CELL_COLUMN_MERGE = 2;
  43.     private static final int IMG_HEIGHT = 30;
  44.     private static final int IMG_WIDTH = 30;
  45.     private static final char LEAN_LINE = '/';
  46.     private static final int BYTES_DEFAULT_LENGTH = 10240;
  47.     private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance();
  48.     public static <T> List<T> readFile(File file, Class<T> clazz) throws Exception {
  49.         JSONArray array = readFile(file);
  50.         return getBeanList(array, clazz);
  51.     }
  52.     public static <T> List<T> readMultipartFile(MultipartFile mFile, Class<T> clazz) throws Exception {
  53.         JSONArray array = readMultipartFile(mFile);
  54.         return getBeanList(array, clazz);
  55.     }
  56.     public static JSONArray readFile(File file) throws Exception {
  57.         return readExcel(null, file);
  58.     }
  59.     public static JSONArray readMultipartFile(MultipartFile mFile) throws Exception {
  60.         return readExcel(mFile, null);
  61.     }
  62.     public static Map<String, JSONArray> readFileManySheet(File file) throws Exception {
  63.         return readExcelManySheet(null, file);
  64.     }
  65.     public static Map<String, JSONArray> readFileManySheet(MultipartFile file) throws Exception {
  66.         return readExcelManySheet(file, null);
  67.     }
  68.     private static <T> List<T> getBeanList(JSONArray array, Class<T> clazz) throws Exception {
  69.         List<T> list = new ArrayList<>();
  70.         Map<Integer, String> uniqueMap = new HashMap<>(16);
  71.         for (int i = 0; i < array.size(); i++) {
  72.             list.add(getBean(clazz, array.getJSONObject(i), uniqueMap));
  73.         }
  74.         return list;
  75.     }
  76.     /**
  77.      * 获取每个对象的数据
  78.      */
  79.     private static <T> T getBean(Class<T> c, JSONObject obj, Map<Integer, String> uniqueMap) throws Exception {
  80.         T t = c.newInstance();
  81.         Field[] fields = c.getDeclaredFields();
  82.         List<String> errMsgList = new ArrayList<>();
  83.         boolean hasRowTipsField = false;
  84.         StringBuilder uniqueBuilder = new StringBuilder();
  85.         int rowNum = 0;
  86.         for (Field field : fields) {
  87.             // 行号
  88.             if (field.getName().equals(ROW_NUM)) {
  89.                 rowNum = obj.getInteger(ROW_NUM);
  90.                 field.setAccessible(true);
  91.                 field.set(t, rowNum);
  92.                 continue;
  93.             }
  94.             // 是否需要设置异常信息
  95.             if (field.getName().equals(ROW_TIPS)) {
  96.                 hasRowTipsField = true;
  97.                 continue;
  98.             }
  99.             // 原始数据
  100.             if (field.getName().equals(ROW_DATA)) {
  101.                 field.setAccessible(true);
  102.                 field.set(t, obj.toString());
  103.                 continue;
  104.             }
  105.             // 设置对应属性值
  106.             setFieldValue(t, field, obj, uniqueBuilder, errMsgList);
  107.         }
  108.         // 数据唯一性校验
  109.         if (uniqueBuilder.length() > 0) {
  110.             if (uniqueMap.containsValue(uniqueBuilder.toString())) {
  111.                 Set<Integer> rowNumKeys = uniqueMap.keySet();
  112.                 for (Integer num : rowNumKeys) {
  113.                     if (uniqueMap.get(num).equals(uniqueBuilder.toString())) {
  114.                         errMsgList.add(String.format("数据唯一性校验失败,(%s)与第%s行重复)", uniqueBuilder, num));
  115.                     }
  116.                 }
  117.             } else {
  118.                 uniqueMap.put(rowNum, uniqueBuilder.toString());
  119.             }
  120.         }
  121.         // 失败处理
  122.         if (errMsgList.isEmpty() && !hasRowTipsField) {
  123.             return t;
  124.         }
  125.         StringBuilder sb = new StringBuilder();
  126.         int size = errMsgList.size();
  127.         for (int i = 0; i < size; i++) {
  128.             if (i == size - 1) {
  129.                 sb.append(errMsgList.get(i));
  130.             } else {
  131.                 sb.append(errMsgList.get(i)).append(";");
  132.             }
  133.         }
  134.         // 设置错误信息
  135.         for (Field field : fields) {
  136.             if (field.getName().equals(ROW_TIPS)) {
  137.                 field.setAccessible(true);
  138.                 field.set(t, sb.toString());
  139.             }
  140.         }
  141.         return t;
  142.     }
  143.     private static <T> void setFieldValue(T t, Field field, JSONObject obj, StringBuilder uniqueBuilder, List<String> errMsgList) {
  144.         // 获取 ExcelImport 注解属性
  145.         ExcelImport annotation = field.getAnnotation(ExcelImport.class);
  146.         if (annotation == null) {
  147.             return;
  148.         }
  149.         String cname = annotation.value();
  150.         if (cname.trim().length() == 0) {
  151.             return;
  152.         }
  153.         // 获取具体值
  154.         String val = null;
  155.         if (obj.containsKey(cname)) {
  156.             val = getString(obj.getString(cname));
  157.         }
  158.         if (val == null) {
  159.             return;
  160.         }
  161.         field.setAccessible(true);
  162.         // 判断是否必填
  163.         boolean require = annotation.required();
  164.         if (require && val.isEmpty()) {
  165.             errMsgList.add(String.format("[%s]不能为空", cname));
  166.             return;
  167.         }
  168.         // 数据唯一性获取
  169.         boolean unique = annotation.unique();
  170.         if (unique) {
  171.             if (uniqueBuilder.length() > 0) {
  172.                 uniqueBuilder.append("--").append(val);
  173.             } else {
  174.                 uniqueBuilder.append(val);
  175.             }
  176.         }
  177.         // 判断是否超过最大长度
  178.         int maxLength = annotation.maxLength();
  179.         if (maxLength > 0 && val.length() > maxLength) {
  180.             errMsgList.add(String.format("[%s]长度不能超过%s个字符(当前%s个字符)", cname, maxLength, val.length()));
  181.         }
  182.         // 判断当前属性是否有映射关系
  183.         LinkedHashMap<String, String> kvMap = getKvMap(annotation.kv());
  184.         if (!kvMap.isEmpty()) {
  185.             boolean isMatch = false;
  186.             for (String key : kvMap.keySet()) {
  187.                 if (kvMap.get(key).equals(val)) {
  188.                     val = key;
  189.                     isMatch = true;
  190.                     break;
  191.                 }
  192.             }
  193.             if (!isMatch) {
  194.                 errMsgList.add(String.format("[%s]的值不正确(当前值为%s)", cname, val));
  195.                 return;
  196.             }
  197.         }
  198.         // 其余情况根据类型赋值
  199.         String fieldClassName = field.getType().getSimpleName();
  200.         try {
  201.             if ("String".equalsIgnoreCase(fieldClassName)) {
  202.                 field.set(t, val);
  203.             } else if ("boolean".equalsIgnoreCase(fieldClassName)) {
  204.                 field.set(t, Boolean.valueOf(val));
  205.             } else if ("int".equalsIgnoreCase(fieldClassName) || "Integer".equals(fieldClassName)) {
  206.                 try {
  207.                     field.set(t, Integer.valueOf(val));
  208.                 } catch (NumberFormatException e) {
  209.                     errMsgList.add(String.format("[%s]的值格式不正确(当前值为%s)", cname, val));
  210.                 }
  211.             } else if ("double".equalsIgnoreCase(fieldClassName)) {
  212.                 field.set(t, Double.valueOf(val));
  213.             } else if ("long".equalsIgnoreCase(fieldClassName)) {
  214.                 field.set(t, Long.valueOf(val));
  215.             } else if ("BigDecimal".equalsIgnoreCase(fieldClassName)) {
  216.                 field.set(t, new BigDecimal(val));
  217.             } else if ("Date".equalsIgnoreCase(fieldClassName)) {
  218.                 try {
  219.                     field.set(t, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(val));
  220.                 } catch (Exception e) {
  221.                     field.set(t, new SimpleDateFormat("yyyy-MM-dd").parse(val));
  222.                 }
  223.             }
  224.         } catch (Exception e) {
  225.             e.printStackTrace();
  226.         }
  227.     }
  228.     private static Map<String, JSONArray> readExcelManySheet(MultipartFile mFile, File file) throws IOException {
  229.         Workbook book = getWorkbook(mFile, file);
  230.         if (book == null) {
  231.             return Collections.emptyMap();
  232.         }
  233.         Map<String, JSONArray> map = new LinkedHashMap<>();
  234.         for (int i = 0; i < book.getNumberOfSheets(); i++) {
  235.             Sheet sheet = book.getSheetAt(i);
  236.             JSONArray arr = readSheet(sheet);
  237.             map.put(sheet.getSheetName(), arr);
  238.         }
  239.         book.close();
  240.         return map;
  241.     }
  242.     private static JSONArray readExcel(MultipartFile mFile, File file) throws IOException {
  243.         Workbook book = getWorkbook(mFile, file);
  244.         if (book == null) {
  245.             return new JSONArray();
  246.         }
  247.         JSONArray array = readSheet(book.getSheetAt(0));
  248.         book.close();
  249.         return array;
  250.     }
  251.     private static Workbook getWorkbook(MultipartFile mFile, File file) throws IOException {
  252.         boolean fileNotExist = (file == null || !file.exists());
  253.         if (mFile == null && fileNotExist) {
  254.             return null;
  255.         }
  256.         // 解析表格数据
  257.         InputStream in;
  258.         String fileName;
  259.         if (mFile != null) {
  260.             // 上传文件解析
  261.             in = mFile.getInputStream();
  262.             fileName = getString(mFile.getOriginalFilename()).toLowerCase();
  263.         } else {
  264.             // 本地文件解析
  265.             in = new FileInputStream(file);
  266.             fileName = file.getName().toLowerCase();
  267.         }
  268.         Workbook book;
  269.         if (fileName.endsWith(XLSX)) {
  270.             book = new XSSFWorkbook(in);
  271.         } else if (fileName.endsWith(XLS)) {
  272.             POIFSFileSystem poifsFileSystem = new POIFSFileSystem(in);
  273.             book = new HSSFWorkbook(poifsFileSystem);
  274.         } else {
  275.             return null;
  276.         }
  277.         in.close();
  278.         return book;
  279.     }
  280.     private static JSONArray readSheet(Sheet sheet) {
  281.         // 首行下标
  282.         int rowStart = sheet.getFirstRowNum();
  283.         // 尾行下标
  284.         int rowEnd = sheet.getLastRowNum();
  285.         // 获取表头行
  286.         Row headRow = sheet.getRow(rowStart);
  287.         if (headRow == null) {
  288.             return new JSONArray();
  289.         }
  290.         int cellStart = headRow.getFirstCellNum();
  291.         int cellEnd = headRow.getLastCellNum();
  292.         Map<Integer, String> keyMap = new HashMap<>();
  293.         for (int j = cellStart; j < cellEnd; j++) {
  294.             // 获取表头数据
  295.             String val = getCellValue(headRow.getCell(j));
  296.             if (val != null && val.trim().length() != 0) {
  297.                 keyMap.put(j, val);
  298.             }
  299.         }
  300.         // 如果表头没有数据则不进行解析
  301.         if (keyMap.isEmpty()) {
  302.             return (JSONArray) Collections.emptyList();
  303.         }
  304.         // 获取每行JSON对象的值
  305.         JSONArray array = new JSONArray();
  306.         // 如果首行与尾行相同,表明只有一行,返回表头数据
  307.         if (rowStart == rowEnd) {
  308.             JSONObject obj = new JSONObject();
  309.             // 添加行号
  310.             obj.put(ROW_NUM, 1);
  311.             for (int i : keyMap.keySet()) {
  312.                 obj.put(keyMap.get(i), "");
  313.             }
  314.             array.add(obj);
  315.             return array;
  316.         }
  317.         for (int i = rowStart + 1; i <= rowEnd; i++) {
  318.             Row eachRow = sheet.getRow(i);
  319.             JSONObject obj = new JSONObject();
  320.             // 添加行号
  321.             obj.put(ROW_NUM, i + 1);
  322.             StringBuilder sb = new StringBuilder();
  323.             for (int k = cellStart; k < cellEnd; k++) {
  324.                 if (eachRow != null) {
  325.                     String val = getCellValue(eachRow.getCell(k));
  326.                     // 所有数据添加到里面,用于判断该行是否为空
  327.                     sb.append(val);
  328.                     obj.put(keyMap.get(k), val);
  329.                 }
  330.             }
  331.             if (sb.length() > 0) {
  332.                 array.add(obj);
  333.             }
  334.         }
  335.         return array;
  336.     }
  337.     private static String getCellValue(Cell cell) {
  338.         // 空白或空
  339.         if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
  340.             return "";
  341.         }
  342.         // String类型
  343.         if (cell.getCellTypeEnum() == CellType.STRING) {
  344.             String val = cell.getStringCellValue();
  345.             if (val == null || val.trim().length() == 0) {
  346.                 return "";
  347.             }
  348.             return val.trim();
  349.         }
  350.         // 数字类型
  351.         if (cell.getCellTypeEnum() == CellType.NUMERIC) {
  352.             String s = cell.getNumericCellValue() + "";
  353.             // 去掉尾巴上的小数点0
  354.             if (Pattern.matches(".*\\.0*", s)) {
  355.                 return s.split("\\.")[0];
  356.             } else {
  357.                 return s;
  358.             }
  359.         }
  360.         // 布尔值类型
  361.         if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
  362.             return cell.getBooleanCellValue() + "";
  363.         }
  364.         // 错误类型
  365.         return cell.getCellFormula();
  366.     }
  367.     public static <T> void exportTemplate(HttpServletResponse response, String fileName, Class<T> clazz) {
  368.         exportTemplate(response, fileName, fileName, clazz, false);
  369.     }
  370.     public static <T> void exportTemplate(HttpServletResponse response, String fileName, String sheetName,
  371.                                           Class<T> clazz) {
  372.         exportTemplate(response, fileName, sheetName, clazz, false);
  373.     }
  374.     public static <T> void exportTemplate(HttpServletResponse response, String fileName, Class<T> clazz,
  375.                                           boolean isContainExample) {
  376.         exportTemplate(response, fileName, fileName, clazz, isContainExample);
  377.     }
  378.     public static <T> void exportTemplate(HttpServletResponse response, String fileName, String sheetName,
  379.                                           Class<T> clazz, boolean isContainExample) {
  380.         // 获取表头字段
  381.         List<ExcelClassField> headFieldList = getExcelClassFieldList(clazz);
  382.         // 获取表头数据和示例数据
  383.         List<List<Object>> sheetDataList = new ArrayList<>();
  384.         List<Object> headList = new ArrayList<>();
  385.         List<Object> exampleList = new ArrayList<>();
  386.         Map<Integer, List<String>> selectMap = new LinkedHashMap<>();
  387.         for (int i = 0; i < headFieldList.size(); i++) {
  388.             ExcelClassField each = headFieldList.get(i);
  389.             headList.add(each.getName());
  390.             exampleList.add(each.getExample());
  391.             LinkedHashMap<String, String> kvMap = each.getKvMap();
  392.             if (kvMap != null && kvMap.size() > 0) {
  393.                 selectMap.put(i, new ArrayList<>(kvMap.values()));
  394.             }
  395.         }
  396.         sheetDataList.add(headList);
  397.         if (isContainExample) {
  398.             sheetDataList.add(exampleList);
  399.         }
  400.         // 导出数据
  401.         export(response, fileName, sheetName, sheetDataList, selectMap);
  402.     }
  403.     private static <T> List<ExcelClassField> getExcelClassFieldList(Class<T> clazz) {
  404.         // 解析所有字段
  405.         Field[] fields = clazz.getDeclaredFields();
  406.         boolean hasExportAnnotation = false;
  407.         Map<Integer, List<ExcelClassField>> map = new LinkedHashMap<>();
  408.         List<Integer> sortList = new ArrayList<>();
  409.         for (Field field : fields) {
  410.             ExcelClassField cf = getExcelClassField(field);
  411.             if (cf.getHasAnnotation() == 1) {
  412.                 hasExportAnnotation = true;
  413.             }
  414.             int sort = cf.getSort();
  415.             if (map.containsKey(sort)) {
  416.                 map.get(sort).add(cf);
  417.             } else {
  418.                 List<ExcelClassField> list = new ArrayList<>();
  419.                 list.add(cf);
  420.                 sortList.add(sort);
  421.                 map.put(sort, list);
  422.             }
  423.         }
  424.         Collections.sort(sortList);
  425.         // 获取表头
  426.         List<ExcelClassField> headFieldList = new ArrayList<>();
  427.         if (hasExportAnnotation) {
  428.             for (Integer sort : sortList) {
  429.                 for (ExcelClassField cf : map.get(sort)) {
  430.                     if (cf.getHasAnnotation() == 1) {
  431.                         headFieldList.add(cf);
  432.                     }
  433.                 }
  434.             }
  435.         } else {
  436.             headFieldList.addAll(map.get(0));
  437.         }
  438.         return headFieldList;
  439.     }
  440.     private static ExcelClassField getExcelClassField(Field field) {
  441.         ExcelClassField cf = new ExcelClassField();
  442.         String fieldName = field.getName();
  443.         cf.setFieldName(fieldName);
  444.         ExcelExport annotation = field.getAnnotation(ExcelExport.class);
  445.         // 无 ExcelExport 注解情况
  446.         if (annotation == null) {
  447.             cf.setHasAnnotation(0);
  448.             cf.setName(fieldName);
  449.             cf.setSort(0);
  450.             return cf;
  451.         }
  452.         // 有 ExcelExport 注解情况
  453.         cf.setHasAnnotation(1);
  454.         cf.setName(annotation.value());
  455.         String example = getString(annotation.example());
  456.         if (!example.isEmpty()) {
  457.             if (isNumeric(example) && example.length() < 8) {
  458.                 cf.setExample(Double.valueOf(example));
  459.             } else {
  460.                 cf.setExample(example);
  461.             }
  462.         } else {
  463.             cf.setExample("");
  464.         }
  465.         cf.setSort(annotation.sort());
  466.         // 解析映射
  467.         String kv = getString(annotation.kv());
  468.         cf.setKvMap(getKvMap(kv));
  469.         return cf;
  470.     }
  471.     private static LinkedHashMap<String, String> getKvMap(String kv) {
  472.         LinkedHashMap<String, String> kvMap = new LinkedHashMap<>();
  473.         if (kv.isEmpty()) {
  474.             return kvMap;
  475.         }
  476.         String[] kvs = kv.split(";");
  477.         if (kvs.length == 0) {
  478.             return kvMap;
  479.         }
  480.         for (String each : kvs) {
  481.             String[] eachKv = getString(each).split("-");
  482.             if (eachKv.length != 2) {
  483.                 continue;
  484.             }
  485.             String k = eachKv[0];
  486.             String v = eachKv[1];
  487.             if (k.isEmpty() || v.isEmpty()) {
  488.                 continue;
  489.             }
  490.             kvMap.put(k, v);
  491.         }
  492.         return kvMap;
  493.     }
  494.     /**
  495.      * 导出表格到本地
  496.      *
  497.      * @param file      本地文件对象
  498.      * @param sheetData 导出数据
  499.      */
  500.     public static void exportFile(File file, List<List<Object>> sheetData) {
  501.         if (file == null) {
  502.             System.out.println("文件创建失败");
  503.             return;
  504.         }
  505.         if (sheetData == null) {
  506.             sheetData = new ArrayList<>();
  507.         }
  508.         Map<String, List<List<Object>>> map = new HashMap<>();
  509.         map.put(file.getName(), sheetData);
  510.         export(null, file, file.getName(), map, null);
  511.     }
  512.     /**
  513.      * 导出表格到本地
  514.      *
  515.      * @param <T>      导出数据类似,和K类型保持一致
  516.      * @param filePath 文件父路径(如:D:/doc/excel/)
  517.      * @param fileName 文件名称(不带尾缀,如:学生表)
  518.      * @param list     导出数据
  519.      * @throws IOException IO异常
  520.      */
  521.     public static <T> File exportFile(String filePath, String fileName, List<T> list) throws IOException {
  522.         File file = getFile(filePath, fileName);
  523.         List<List<Object>> sheetData = getSheetData(list);
  524.         exportFile(file, sheetData);
  525.         return file;
  526.     }
  527.     /**
  528.      * 获取文件
  529.      *
  530.      * @param filePath filePath 文件父路径(如:D:/doc/excel/)
  531.      * @param fileName 文件名称(不带尾缀,如:用户表)
  532.      * @return 本地File文件对象
  533.      */
  534.     private static File getFile(String filePath, String fileName) throws IOException {
  535.         String dirPath = getString(filePath);
  536.         String fileFullPath;
  537.         if (dirPath.isEmpty()) {
  538.             fileFullPath = fileName;
  539.         } else {
  540.             // 判定文件夹是否存在,如果不存在,则级联创建
  541.             File dirFile = new File(dirPath);
  542.             if (!dirFile.exists()) {
  543.                 boolean mkdirs = dirFile.mkdirs();
  544.                 if (!mkdirs) {
  545.                     return null;
  546.                 }
  547.             }
  548.             // 获取文件夹全名
  549.             if (dirPath.endsWith(String.valueOf(LEAN_LINE))) {
  550.                 fileFullPath = dirPath + fileName + XLSX;
  551.             } else {
  552.                 fileFullPath = dirPath + LEAN_LINE + fileName + XLSX;
  553.             }
  554.         }
  555.         System.out.println(fileFullPath);
  556.         File file = new File(fileFullPath);
  557.         if (!file.exists()) {
  558.             boolean result = file.createNewFile();
  559.             if (!result) {
  560.                 return null;
  561.             }
  562.         }
  563.         return file;
  564.     }
  565.     private static <T> List<List<Object>> getSheetData(List<T> list) {
  566.         // 获取表头字段
  567.         List<ExcelClassField> excelClassFieldList = getExcelClassFieldList(list.get(0).getClass());
  568.         List<String> headFieldList = new ArrayList<>();
  569.         List<Object> headList = new ArrayList<>();
  570.         Map<String, ExcelClassField> headFieldMap = new HashMap<>();
  571.         for (ExcelClassField each : excelClassFieldList) {
  572.             String fieldName = each.getFieldName();
  573.             headFieldList.add(fieldName);
  574.             headFieldMap.put(fieldName, each);
  575.             headList.add(each.getName());
  576.         }
  577.         // 添加表头名称
  578.         List<List<Object>> sheetDataList = new ArrayList<>();
  579.         sheetDataList.add(headList);
  580.         // 获取表数据
  581.         for (T t : list) {
  582.             Map<String, Object> fieldDataMap = getFieldDataMap(t);
  583.             Set<String> fieldDataKeys = fieldDataMap.keySet();
  584.             List<Object> rowList = new ArrayList<>();
  585.             for (String headField : headFieldList) {
  586.                 if (!fieldDataKeys.contains(headField)) {
  587.                     continue;
  588.                 }
  589.                 Object data = fieldDataMap.get(headField);
  590.                 if (data == null) {
  591.                     rowList.add("");
  592.                     continue;
  593.                 }
  594.                 ExcelClassField cf = headFieldMap.get(headField);
  595.                 // 判断是否有映射关系
  596.                 LinkedHashMap<String, String> kvMap = cf.getKvMap();
  597.                 if (kvMap == null || kvMap.isEmpty()) {
  598.                     rowList.add(data);
  599.                     continue;
  600.                 }
  601.                 String val = kvMap.get(data.toString());
  602.                 if (isNumeric(val)) {
  603.                     rowList.add(Double.valueOf(val));
  604.                 } else {
  605.                     rowList.add(val);
  606.                 }
  607.             }
  608.             sheetDataList.add(rowList);
  609.         }
  610.         return sheetDataList;
  611.     }
  612.     private static <T> Map<String, Object> getFieldDataMap(T t) {
  613.         Map<String, Object> map = new HashMap<>();
  614.         Field[] fields = t.getClass().getDeclaredFields();
  615.         try {
  616.             for (Field field : fields) {
  617.                 String fieldName = field.getName();
  618.                 field.setAccessible(true);
  619.                 Object object = field.get(t);
  620.                 map.put(fieldName, object);
  621.             }
  622.         } catch (IllegalArgumentException | IllegalAccessException e) {
  623.             e.printStackTrace();
  624.         }
  625.         return map;
  626.     }
  627.     public static void exportEmpty(HttpServletResponse response, String fileName) {
  628.         List<List<Object>> sheetDataList = new ArrayList<>();
  629.         List<Object> headList = new ArrayList<>();
  630.         headList.add("导出无数据");
  631.         sheetDataList.add(headList);
  632.         export(response, fileName, sheetDataList);
  633.     }
  634.     public static void export(HttpServletResponse response, String fileName, List<List<Object>> sheetDataList) {
  635.         export(response, fileName, fileName, sheetDataList, null);
  636.     }
  637.     public static void exportManySheet(HttpServletResponse response, String fileName, Map<String, List<List<Object>>> sheetMap) {
  638.         export(response, null, fileName, sheetMap, null);
  639.     }
  640.     public static void export(HttpServletResponse response, String fileName, String sheetName,
  641.                               List<List<Object>> sheetDataList) {
  642.         export(response, fileName, sheetName, sheetDataList, null);
  643.     }
  644.     public static void export(HttpServletResponse response, String fileName, String sheetName,
  645.                               List<List<Object>> sheetDataList, Map<Integer, List<String>> selectMap) {
  646.         Map<String, List<List<Object>>> map = new HashMap<>();
  647.         map.put(sheetName, sheetDataList);
  648.         export(response, null, fileName, map, selectMap);
  649.     }
  650.     public static <T, K> void export(HttpServletResponse response, String fileName, List<T> list, Class<K> template) {
  651.         // list 是否为空
  652.         boolean lisIsEmpty = list == null || list.isEmpty();
  653.         // 如果模板数据为空,且导入的数据为空,则导出空文件
  654.         if (template == null && lisIsEmpty) {
  655.             exportEmpty(response, fileName);
  656.             return;
  657.         }
  658.         // 如果 list 数据,则导出模板数据
  659.         if (lisIsEmpty) {
  660.             exportTemplate(response, fileName, template);
  661.             return;
  662.         }
  663.         // 导出数据
  664.         List<List<Object>> sheetDataList = getSheetData(list);
  665.         export(response, fileName, sheetDataList);
  666.     }
  667.     public static void export(HttpServletResponse response, String fileName, List<List<Object>> sheetDataList, Map<Integer, List<String>> selectMap) {
  668.         export(response, fileName, fileName, sheetDataList, selectMap);
  669.     }
  670.     private static void export(HttpServletResponse response, File file, String fileName,
  671.                                Map<String, List<List<Object>>> sheetMap, Map<Integer, List<String>> selectMap) {
  672.         // 整个 Excel 表格 book 对象
  673.         SXSSFWorkbook book = new SXSSFWorkbook();
  674.         // 每个 Sheet 页
  675.         Set<Entry<String, List<List<Object>>>> entries = sheetMap.entrySet();
  676.         for (Entry<String, List<List<Object>>> entry : entries) {
  677.             List<List<Object>> sheetDataList = entry.getValue();
  678.             Sheet sheet = book.createSheet(entry.getKey());
  679.             Drawing<?> patriarch = sheet.createDrawingPatriarch();
  680.             // 设置表头背景色(灰色)
  681.             CellStyle headStyle = book.createCellStyle();
  682.             headStyle.setFillForegroundColor(IndexedColors.GREY_80_PERCENT.index);
  683.             headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  684.             headStyle.setAlignment(HorizontalAlignment.CENTER);
  685.             headStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
  686.             // 设置表身背景色(默认色)
  687.             CellStyle rowStyle = book.createCellStyle();
  688.             rowStyle.setAlignment(HorizontalAlignment.CENTER);
  689.             rowStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  690.             // 设置表格列宽度(默认为15个字节)
  691.             sheet.setDefaultColumnWidth(15);
  692.             // 创建合并算法数组
  693.             int rowLength = sheetDataList.size();
  694.             int columnLength = sheetDataList.get(0).size();
  695.             int[][] mergeArray = new int[rowLength][columnLength];
  696.             for (int i = 0; i < sheetDataList.size(); i++) {
  697.                 // 每个 Sheet 页中的行数据
  698.                 Row row = sheet.createRow(i);
  699.                 List<Object> rowList = sheetDataList.get(i);
  700.                 for (int j = 0; j < rowList.size(); j++) {
  701.                     // 每个行数据中的单元格数据
  702.                     Object o = rowList.get(j);
  703.                     int v = 0;
  704.                     if (o instanceof URL) {
  705.                         // 如果要导出图片的话, 链接需要传递 URL 对象
  706.                         setCellPicture(book, row, patriarch, i, j, (URL) o);
  707.                     } else {
  708.                         Cell cell = row.createCell(j);
  709.                         if (i == 0) {
  710.                             // 第一行为表头行,采用灰色底背景
  711.                             v = setCellValue(cell, o, headStyle);
  712.                         } else {
  713.                             // 其他行为数据行,默认白底色
  714.                             v = setCellValue(cell, o, rowStyle);
  715.                         }
  716.                     }
  717.                     mergeArray[i][j] = v;
  718.                 }
  719.             }
  720.             // 合并单元格
  721.             mergeCells(sheet, mergeArray);
  722.             // 设置下拉列表
  723.             setSelect(sheet, selectMap);
  724.         }
  725.         // 写数据
  726.         if (response != null) {
  727.             // 前端导出
  728.             try {
  729.                 write(response, book, fileName);
  730.             } catch (IOException e) {
  731.                 e.printStackTrace();
  732.             }
  733.         } else {
  734.             // 本地导出
  735.             FileOutputStream fos;
  736.             try {
  737.                 fos = new FileOutputStream(file);
  738.                 ByteArrayOutputStream ops = new ByteArrayOutputStream();
  739.                 book.write(ops);
  740.                 fos.write(ops.toByteArray());
  741.                 fos.close();
  742.             } catch (Exception e) {
  743.                 e.printStackTrace();
  744.             }
  745.         }
  746.     }
  747.     /**
  748.      * 合并当前Sheet页的单元格
  749.      *
  750.      * @param sheet      当前 sheet 页
  751.      * @param mergeArray 合并单元格算法
  752.      */
  753.     private static void mergeCells(Sheet sheet, int[][] mergeArray) {
  754.         // 横向合并
  755.         for (int x = 0; x < mergeArray.length; x++) {
  756.             int[] arr = mergeArray[x];
  757.             boolean merge = false;
  758.             int y1 = 0;
  759.             int y2 = 0;
  760.             for (int y = 0; y < arr.length; y++) {
  761.                 int value = arr[y];
  762.                 if (value == CELL_COLUMN_MERGE) {
  763.                     if (!merge) {
  764.                         y1 = y;
  765.                     }
  766.                     y2 = y;
  767.                     merge = true;
  768.                 } else {
  769.                     merge = false;
  770.                     if (y1 > 0) {
  771.                         sheet.addMergedRegion(new CellRangeAddress(x, x, (y1 - 1), y2));
  772.                     }
  773.                     y1 = 0;
  774.                     y2 = 0;
  775.                 }
  776.             }
  777.             if (y1 > 0) {
  778.                 sheet.addMergedRegion(new CellRangeAddress(x, x, (y1 - 1), y2));
  779.             }
  780.         }
  781.         // 纵向合并
  782.         int xLen = mergeArray.length;
  783.         int yLen = mergeArray[0].length;
  784.         for (int y = 0; y < yLen; y++) {
  785.             boolean merge = false;
  786.             int x1 = 0;
  787.             int x2 = 0;
  788.             for (int x = 0; x < xLen; x++) {
  789.                 int value = mergeArray[x][y];
  790.                 if (value == CELL_ROW_MERGE) {
  791.                     if (!merge) {
  792.                         x1 = x;
  793.                     }
  794.                     x2 = x;
  795.                     merge = true;
  796.                 } else {
  797.                     merge = false;
  798.                     if (x1 > 0) {
  799.                         sheet.addMergedRegion(new CellRangeAddress((x1 - 1), x2, y, y));
  800.                     }
  801.                     x1 = 0;
  802.                     x2 = 0;
  803.                 }
  804.             }
  805.             if (x1 > 0) {
  806.                 sheet.addMergedRegion(new CellRangeAddress((x1 - 1), x2, y, y));
  807.             }
  808.         }
  809.     }
  810.     private static void write(HttpServletResponse response, SXSSFWorkbook book, String fileName) throws IOException {
  811.         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  812.         response.setCharacterEncoding("utf-8");
  813.         String name = new String(fileName.getBytes("GBK"), "ISO8859_1") + XLSX;
  814.         response.addHeader("Content-Disposition", "attachment;filename=" + name);
  815.         ServletOutputStream out = response.getOutputStream();
  816.         book.write(out);
  817.         out.flush();
  818.         out.close();
  819.     }
  820.     private static int setCellValue(Cell cell, Object o, CellStyle style) {
  821.         // 设置样式
  822.         cell.setCellStyle(style);
  823.         // 数据为空时
  824.         if (o == null) {
  825.             cell.setCellType(CellType.STRING);
  826.             cell.setCellValue("");
  827.             return CELL_OTHER;
  828.         }
  829.         // 是否为字符串
  830.         if (o instanceof String) {
  831.             String s = o.toString();
  832.             // 当数字类型长度超过8位时,改为字符串类型显示(Excel数字超过一定长度会显示为科学计数法)
  833.             if (isNumeric(s) && s.length() < 8) {
  834.                 cell.setCellType(CellType.NUMERIC);
  835.                 cell.setCellValue(Double.parseDouble(s));
  836.                 return CELL_OTHER;
  837.             } else {
  838.                 cell.setCellType(CellType.STRING);
  839.                 cell.setCellValue(s);
  840.             }
  841.             if (s.equals(ROW_MERGE)) {
  842.                 return CELL_ROW_MERGE;
  843.             } else if (s.equals(COLUMN_MERGE)) {
  844.                 return CELL_COLUMN_MERGE;
  845.             } else {
  846.                 return CELL_OTHER;
  847.             }
  848.         }
  849.         // 是否为字符串
  850.         if (o instanceof Integer || o instanceof Long || o instanceof Double || o instanceof Float) {
  851.             cell.setCellType(CellType.NUMERIC);
  852.             cell.setCellValue(Double.parseDouble(o.toString()));
  853.             return CELL_OTHER;
  854.         }
  855.         // 是否为Boolean
  856.         if (o instanceof Boolean) {
  857.             cell.setCellType(CellType.BOOLEAN);
  858.             cell.setCellValue((Boolean) o);
  859.             return CELL_OTHER;
  860.         }
  861.         // 如果是BigDecimal,则默认3位小数
  862.         if (o instanceof BigDecimal) {
  863.             cell.setCellType(CellType.NUMERIC);
  864.             cell.setCellValue(((BigDecimal) o).setScale(3, RoundingMode.HALF_UP).doubleValue());
  865.             return CELL_OTHER;
  866.         }
  867.         // 如果是Date数据,则显示格式化数据
  868.         if (o instanceof Date) {
  869.             cell.setCellType(CellType.STRING);
  870.             cell.setCellValue(formatDate((Date) o));
  871.             return CELL_OTHER;
  872.         }
  873.         // 如果是其他,则默认字符串类型
  874.         cell.setCellType(CellType.STRING);
  875.         cell.setCellValue(o.toString());
  876.         return CELL_OTHER;
  877.     }
  878.     private static void setCellPicture(SXSSFWorkbook wb, Row sr, Drawing<?> patriarch, int x, int y, URL url) {
  879.         // 设置图片宽高
  880.         sr.setHeight((short) (IMG_WIDTH * IMG_HEIGHT));
  881.         // (jdk1.7版本try中定义流可自动关闭)
  882.         try (InputStream is = url.openStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
  883.             byte[] buff = new byte[BYTES_DEFAULT_LENGTH];
  884.             int rc;
  885.             while ((rc = is.read(buff, 0, BYTES_DEFAULT_LENGTH)) > 0) {
  886.                 outputStream.write(buff, 0, rc);
  887.             }
  888.             // 设置图片位置
  889.             XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, y, x, y + 1, x + 1);
  890.             // 设置这个,图片会自动填满单元格的长宽
  891.             anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE);
  892.             patriarch.createPicture(anchor, wb.addPicture(outputStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
  893.         } catch (Exception e) {
  894.             e.printStackTrace();
  895.         }
  896.     }
  897.     private static String formatDate(Date date) {
  898.         if (date == null) {
  899.             return "";
  900.         }
  901.         SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
  902.         return format.format(date);
  903.     }
  904.     private static void setSelect(Sheet sheet, Map<Integer, List<String>> selectMap) {
  905.         if (selectMap == null || selectMap.isEmpty()) {
  906.             return;
  907.         }
  908.         Set<Entry<Integer, List<String>>> entrySet = selectMap.entrySet();
  909.         for (Entry<Integer, List<String>> entry : entrySet) {
  910.             int y = entry.getKey();
  911.             List<String> list = entry.getValue();
  912.             if (list == null || list.isEmpty()) {
  913.                 continue;
  914.             }
  915.             String[] arr = new String[list.size()];
  916.             for (int i = 0; i < list.size(); i++) {
  917.                 arr[i] = list.get(i);
  918.             }
  919.             DataValidationHelper helper = sheet.getDataValidationHelper();
  920.             CellRangeAddressList addressList = new CellRangeAddressList(1, 65000, y, y);
  921.             DataValidationConstraint dvc = helper.createExplicitListConstraint(arr);
  922.             DataValidation dv = helper.createValidation(dvc, addressList);
  923.             if (dv instanceof HSSFDataValidation) {
  924.                 dv.setSuppressDropDownArrow(false);
  925.             } else {
  926.                 dv.setSuppressDropDownArrow(true);
  927.                 dv.setShowErrorBox(true);
  928.             }
  929.             sheet.addValidationData(dv);
  930.         }
  931.     }
  932.     private static boolean isNumeric(String str) {
  933.         if (Objects.nonNull(str) && "0.0".equals(str)) {
  934.             return true;
  935.         }
  936.         for (int i = str.length(); --i >= 0; ) {
  937.             if (!Character.isDigit(str.charAt(i))) {
  938.                 return false;
  939.             }
  940.         }
  941.         return true;
  942.     }
  943.     private static String getString(String s) {
  944.         if (s == null) {
  945.             return "";
  946.         }
  947.         if (s.isEmpty()) {
  948.             return s;
  949.         }
  950.         return s.trim();
  951.     }
  952. }
复制代码
3.Excel导出配置
  1. package com.information.utils;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7.    导出配置
  8. */
  9. @Target(ElementType.FIELD)
  10. @Retention(RetentionPolicy.RUNTIME)
  11. public @interface ExcelExport {
  12.     /** 字段名称 */
  13.     String value();
  14.     /** 导出排序先后: 数字越小越靠前(默认按Java类字段顺序导出) */
  15.     int sort() default 0;
  16.     /** 导出映射,格式如:0-未知;1-男;2-女 */
  17.     String kv() default "";
  18.     /** 导出模板示例值(有值的话,直接取该值,不做映射) */
  19.     String example() default "";
  20. }
复制代码
4.Excel导入配置
  1. package com.information.utils;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7.    导入配置
  8. */
  9. @Target(ElementType.FIELD)
  10. @Retention(RetentionPolicy.RUNTIME)
  11. public @interface ExcelImport {
  12.     /** 字段名称 */
  13.     String value();
  14.     /** 导出映射,格式如:0-未知;1-男;2-女 */
  15.     String kv() default "";
  16.     /** 是否为必填字段(默认为非必填) */
  17.     boolean required() default false;
  18.     /** 最大长度(默认255) */
  19.     int maxLength() default 255;
  20.     /** 导入唯一性验证(多个字段则取联合验证) */
  21.     boolean unique() default false;
  22. }
复制代码
 
三、添加user表和工具类使用方法

1.user表设置
  1. package com.information.pojo;
  2. import com.information.utils.ExcelExport;
  3. import com.information.utils.ExcelImport;
  4. import lombok.Data;
  5. import lombok.Value;
  6. @Data
  7. public class ExcelUser {
  8.     //导入时候获取数据行号--第几行
  9.     private int rowNum;
  10.     //数据导入的时候,如果某行存在错误,一般我们会将原始的数据拿出来分析--get这个字段即可
  11.     private String rowData;
  12.     //导入数据的时候,如果某行数据存在字段类型不正确 则会提示对应的错误信息
  13.     private String rowTips;
  14.     //ExcelImport 导入工具类中 required = true 添加必填项 unique = true 标识唯一性不可重复
  15.     @ExcelImport(value = "姓名")
  16.     @ExcelExport(value = "姓名",example = "张三")
  17.     private String name;
  18.     //ExcelImport 导入的设置
  19.     //ExcelExport 导出的设置
  20.     @ExcelImport("年龄")
  21.     @ExcelExport(value = "年龄",example = "18")
  22.     private Integer age;
  23.     //在导入数据的时候将男女自动转换1--2
  24.     @ExcelImport(value = "性别",kv = "1-男;2-女")
  25.     //在导出数据的时候将男女自动转换1--2
  26.     @ExcelExport(value = "性别",example = "男",kv = "1-男;2-女")
  27.     private String sex;
  28.     //maxLength = 11 电话控制大小
  29.     //ExcelExport 导出工具类中 example 的意思是 下载样式模版的时候添加的一条样式数据
  30.     @ExcelImport(value = "电话")
  31.     @ExcelExport(value = "电话",example = "13333333333")
  32.     private String tel;
  33.     @ExcelImport("城市")
  34.     @ExcelExport(value = "城市",example = "上海")
  35.     private String city;
  36.     @ExcelImport("头像")
  37.     @ExcelExport(value = "城市",example = "www.touxiang.com")
  38.     private String avatar;
  39. }
复制代码
 
2.工具类的使用
  1. /**
  2.      * 此方法在导入的时候 1男 2 女 sex=1性别自动转换  
  3.      * rowNum=2 自动获取Excel 数据行数
  4.      *  RowTips  提醒错误信息
  5.      * @param file
  6.      * @throws Exception
  7.      */
  8.     @PostMapping("/import")
  9.     @ResponseBody
  10.     public JSONObject importUser(@RequestPart("file")MultipartFile file) throws Exception {
  11.         List<ExcelUser> users = ExcelUtils.readMultipartFile(file, ExcelUser.class);
  12.         for (ExcelUser user : users) {
  13.             JSONObject object = new JSONObject();
  14.             System.out.println(user.getSex());
  15.             System.out.println(user.getName());
  16.             System.out.println(user.getAge());
  17.             System.out.println(user.getTel());
  18.             System.out.println(user.getCity());
  19.             System.out.println(user.getAvatar());
  20.             //错误提示
  21.             System.out.println(user.getRowTips());
  22.             //列如我们手机号在user表中设置 长度11 那么在导入的时候你是12
  23.             //将提示您的第2行数据的手机号码超过11位
  24.             object.put(Consts.MSG,"您的第"+user.getRowNum()+"行"+user.getRowTips());
  25.             object.put(Consts.CODE,"0");
  26.             return object;
  27.         }
  28.         return null;
  29.     }
  30.     /**
  31.      * 导入多Sheet页
  32.      * @param file
  33.      * @throws Exception
  34.      */
  35.     @PostMapping("/import1")
  36.     @ResponseBody
  37.     public void upload(@RequestPart("file") MultipartFile file) throws Exception {
  38.         Map<String, JSONArray> map = ExcelUtils.readFileManySheet(file);
  39.         map.forEach((key, value) -> {
  40.             System.out.println("Sheet名称:" + key);
  41.             System.out.println("Sheet数据:" + value);
  42.             System.out.println("----------------------");
  43.         });
  44.     }
  45.     /**
  46.      * 下载样式模版
  47.      * 也就是我们在对象表中设置的example关键字
  48.      * @param response
  49.      */
  50.     @GetMapping("/export")
  51.     @ResponseBody
  52.     public void export(HttpServletResponse response) {
  53.         ExcelUtils.exportTemplate(response, "用户表", ExcelUser.class,true);
  54.     }
  55.     /**
  56.      * 下载查询数据--导出
  57.      * @param response
  58.      */
  59.     @GetMapping("/exportdc")
  60.     public void exportdc(HttpServletResponse response) {
  61.         List<ExcelUser> userList = new ArrayList<>();
  62.         ExcelUser user1 = new ExcelUser();
  63.         user1.setName("张三");
  64.         user1.setAge (18);
  65.         //性别我们也有设置 1男2女
  66.         //ExcelImport导入的设置
  67.         //@ExcelImport(value = "性别",kv = "1-男;2-女")
  68.         //ExcelExport 导出的设置
  69.         //@ExcelExport(value = "性别",kv = "1-男;2-女")
  70.         user1.setSex("1");
  71.         user1.setCity("成都");
  72.         user1.setTel("13800000");
  73.         user1.setAvatar("www");
  74.         userList.add(user1);
  75.         ExcelUtils.export(response,  "用户表", userList, ExcelUser.class);
  76.     }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

天空闲话

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表