当前位置:   article > 正文

java导出excel(带图片)_java导出excel带图片

java导出excel带图片

先看一下导出效果,

controller

表头数据一定要放在最前面

List<Object> head = Arrays.asList("姓名","年龄","性别","证件类别","证件号","联系电话","地区","详细地址","报名时间","所属分组","年度","参赛类别1","作品名称1","作品1","参赛类别2","作品名称2","作品2");

List<List<Object>> sheetDataList = new ArrayList<>();

sheetDataList.add(head);

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

闽ICP备14008679号