当前位置:   article > 正文

Springboot导出mysql数据到Excel表

Springboot导出mysql数据到Excel表

Controller层代码

  1. /**
  2. * 导出数据管理审核表
  3. */
  4. @ApiOperation(value = "导出数据管理审核表")
  5. @Log(title = "导出数据管理审核表", businessType = BusinessType.EXPORT)
  6. @PostMapping("/exportCsv")
  7. public void exportCsv(HttpServletResponse response, @Param("tableName") String tableName, @Param("tableType") Integer tableType) {
  8. List<DataProductionAnnotationOneVo> oneList = dataCommonOperationMapper.selectCsvByPass(tableName);
  9. ExcelUtil<DataProductionAnnotationOneVo> util = new ExcelUtil<DataProductionAnnotationOneVo>(DataProductionAnnotationOneVo.class);
  10. util.exportExcel(response, oneList, tableName);
  11. }

实体类代码

  1. import com.baomidou.mybatisplus.annotation.TableName;
  2. import com.fasterxml.jackson.annotation.JsonFormat;
  3. import com.geb.common.annotation.Excel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.Data;
  6. import java.io.Serializable;
  7. import java.util.Date;
  8. @Data
  9. @TableName("data_production_annotation_one")
  10. public class DataProductionAnnotationOneVo implements Serializable {
  11. private static final long serialVersionUID = 1L;
  12. /**
  13. * 主键id
  14. */
  15. @Excel(name = "id", cellType = Excel.ColumnType.NUMERIC)
  16. private Long id;
  17. /**
  18. * 部署id
  19. */
  20. @Excel(name = "deployId", cellType = Excel.ColumnType.NUMERIC)
  21. private Long deployId;
  22. /**
  23. * 推理参数表id
  24. */
  25. @Excel(name = "parameterId", cellType = Excel.ColumnType.NUMERIC)
  26. private Long parameterId;
  27. /**
  28. * 空间
  29. */
  30. @Excel(name = "space")
  31. private String space;
  32. /**
  33. * 设备
  34. */
  35. @Excel(name = "device")
  36. private String device;
  37. /**
  38. * 场景
  39. */
  40. @Excel(name = "scene")
  41. private String scene;
  42. /**
  43. * 位置
  44. */
  45. @Excel(name = "position")
  46. private String position;
  47. /**
  48. * 操作指令
  49. */
  50. @Excel(name = "query")
  51. private String query;
  52. /**
  53. * 模板id
  54. */
  55. @Excel(name = "promptId", cellType = Excel.ColumnType.NUMERIC)
  56. private Long promptId;
  57. /**
  58. * 回答
  59. */
  60. @Excel(name = "model_return")
  61. private String model_return;
  62. /**
  63. * 数据审核状态(1:待审核 2:审核通过 3:已驳回)
  64. */
  65. @ApiModelProperty("数据审核状态(1:待审核 2:审核通过 3:已驳回)")
  66. @Excel(name = "auditStatus", readConverterExp = "1=待审核,2=审核通过,3=已驳回")
  67. private Integer auditStatus;
  68. /**
  69. * 数据审核意见
  70. */
  71. @ApiModelProperty("数据审核意见")
  72. @Excel(name = "auditMsg")
  73. private String auditMsg;
  74. /**
  75. * 审核人
  76. */
  77. @ApiModelProperty("审核人")
  78. @Excel(name = "auditBy")
  79. private String auditBy;
  80. /**
  81. * 审核人id
  82. */
  83. @ApiModelProperty("审核人id")
  84. @Excel(name = "auditById", cellType = Excel.ColumnType.NUMERIC)
  85. private Long auditById;
  86. /**
  87. * 审核时间
  88. */
  89. @ApiModelProperty("审核时间")
  90. @JsonFormat(pattern = "yyyy-MM-dd HH:mm")
  91. @Excel(name = "auditTime", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Excel.Type.EXPORT)
  92. private Date auditTime;
  93. /**
  94. * 创建人
  95. */
  96. @ApiModelProperty("创建人")
  97. @Excel(name = "createBy")
  98. private String createBy;
  99. /**
  100. * 创建时间
  101. */
  102. @ApiModelProperty("创建时间")
  103. @JsonFormat(pattern = "yyyy-MM-dd HH:mm")
  104. @Excel(name = "createTime", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Excel.Type.EXPORT)
  105. private Date createTime;
  106. /**
  107. * 创建者id
  108. */
  109. @ApiModelProperty("创建者id")
  110. @Excel(name = "createById", cellType = Excel.ColumnType.NUMERIC)
  111. private Long createById;
  112. /**
  113. * 更新人
  114. */
  115. @ApiModelProperty("更新人")
  116. @Excel(name = "updateBy")
  117. private String updateBy;
  118. /**
  119. * 更新人id
  120. */
  121. @ApiModelProperty("更新人id")
  122. @Excel(name = "updateById", cellType = Excel.ColumnType.NUMERIC)
  123. private Long updateById;
  124. /**
  125. * 更新时间
  126. */
  127. @ApiModelProperty("更新时间")
  128. @JsonFormat(pattern = "yyyy-MM-dd HH:mm")
  129. @Excel(name = "updateTime", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Excel.Type.EXPORT)
  130. private Date updateTime;
  131. }

ExcelUtil工具类代码

  1. package com.geb.common.utils.poi;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.lang.reflect.Field;
  8. import java.lang.reflect.Method;
  9. import java.lang.reflect.ParameterizedType;
  10. import java.math.BigDecimal;
  11. import java.text.DecimalFormat;
  12. import java.time.LocalDate;
  13. import java.time.LocalDateTime;
  14. import java.util.ArrayList;
  15. import java.util.Arrays;
  16. import java.util.Collection;
  17. import java.util.Comparator;
  18. import java.util.Date;
  19. import java.util.HashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Set;
  23. import java.util.UUID;
  24. import java.util.stream.Collectors;
  25. import javax.servlet.http.HttpServletResponse;
  26. import org.apache.commons.lang3.ArrayUtils;
  27. import org.apache.commons.lang3.RegExUtils;
  28. import org.apache.commons.lang3.reflect.FieldUtils;
  29. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
  30. import org.apache.poi.hssf.usermodel.HSSFPicture;
  31. import org.apache.poi.hssf.usermodel.HSSFPictureData;
  32. import org.apache.poi.hssf.usermodel.HSSFShape;
  33. import org.apache.poi.hssf.usermodel.HSSFSheet;
  34. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  35. import org.apache.poi.ooxml.POIXMLDocumentPart;
  36. import org.apache.poi.ss.usermodel.BorderStyle;
  37. import org.apache.poi.ss.usermodel.Cell;
  38. import org.apache.poi.ss.usermodel.CellStyle;
  39. import org.apache.poi.ss.usermodel.CellType;
  40. import org.apache.poi.ss.usermodel.ClientAnchor;
  41. import org.apache.poi.ss.usermodel.DataValidation;
  42. import org.apache.poi.ss.usermodel.DataValidationConstraint;
  43. import org.apache.poi.ss.usermodel.DataValidationHelper;
  44. import org.apache.poi.ss.usermodel.DateUtil;
  45. import org.apache.poi.ss.usermodel.Drawing;
  46. import org.apache.poi.ss.usermodel.FillPatternType;
  47. import org.apache.poi.ss.usermodel.Font;
  48. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  49. import org.apache.poi.ss.usermodel.IndexedColors;
  50. import org.apache.poi.ss.usermodel.Name;
  51. import org.apache.poi.ss.usermodel.PictureData;
  52. import org.apache.poi.ss.usermodel.Row;
  53. import org.apache.poi.ss.usermodel.Sheet;
  54. import org.apache.poi.ss.usermodel.VerticalAlignment;
  55. import org.apache.poi.ss.usermodel.Workbook;
  56. import org.apache.poi.ss.usermodel.WorkbookFactory;
  57. import org.apache.poi.ss.util.CellRangeAddress;
  58. import org.apache.poi.ss.util.CellRangeAddressList;
  59. import org.apache.poi.util.IOUtils;
  60. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  61. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
  62. import org.apache.poi.xssf.usermodel.XSSFDataValidation;
  63. import org.apache.poi.xssf.usermodel.XSSFDrawing;
  64. import org.apache.poi.xssf.usermodel.XSSFPicture;
  65. import org.apache.poi.xssf.usermodel.XSSFShape;
  66. import org.apache.poi.xssf.usermodel.XSSFSheet;
  67. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  68. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
  69. import org.slf4j.Logger;
  70. import org.slf4j.LoggerFactory;
  71. import com.geb.common.annotation.Excel;
  72. import com.geb.common.annotation.Excel.ColumnType;
  73. import com.geb.common.annotation.Excel.Type;
  74. import com.geb.common.annotation.Excels;
  75. import com.geb.common.config.RuoYiConfig;
  76. import com.geb.common.core.domain.AjaxResult;
  77. import com.geb.common.core.text.Convert;
  78. import com.geb.common.exception.UtilException;
  79. import com.geb.common.utils.DateUtils;
  80. import com.geb.common.utils.DictUtils;
  81. import com.geb.common.utils.StringUtils;
  82. import com.geb.common.utils.file.FileTypeUtils;
  83. import com.geb.common.utils.file.FileUtils;
  84. import com.geb.common.utils.file.ImageUtils;
  85. import com.geb.common.utils.reflect.ReflectUtils;
  86. /**
  87. * Excel相关处理
  88. *
  89. * @author ruoyi
  90. */
  91. public class ExcelUtil<T>
  92. {
  93. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  94. public static final String FORMULA_REGEX_STR = "=|-|\\+|@";
  95. public static final String[] FORMULA_STR = { "=", "-", "+", "@" };
  96. /**
  97. * 用于dictType属性数据存储,避免重复查缓存
  98. */
  99. public Map<String, String> sysDictMap = new HashMap<String, String>();
  100. /**
  101. * Excel sheet最大行数,默认65536
  102. */
  103. public static final int sheetSize = 65536;
  104. /**
  105. * 工作表名称
  106. */
  107. private String sheetName;
  108. /**
  109. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
  110. */
  111. private Type type;
  112. /**
  113. * 工作薄对象
  114. */
  115. private Workbook wb;
  116. /**
  117. * 工作表对象
  118. */
  119. private Sheet sheet;
  120. /**
  121. * 样式列表
  122. */
  123. private Map<String, CellStyle> styles;
  124. /**
  125. * 导入导出数据列表
  126. */
  127. private List<T> list;
  128. /**
  129. * 注解列表
  130. */
  131. private List<Object[]> fields;
  132. /**
  133. * 当前行号
  134. */
  135. private int rownum;
  136. /**
  137. * 标题
  138. */
  139. private String title;
  140. /**
  141. * 最大高度
  142. */
  143. private short maxHeight;
  144. /**
  145. * 合并后最后行数
  146. */
  147. private int subMergedLastRowNum = 0;
  148. /**
  149. * 合并后开始行数
  150. */
  151. private int subMergedFirstRowNum = 1;
  152. /**
  153. * 对象的子列表方法
  154. */
  155. private Method subMethod;
  156. /**
  157. * 对象的子列表属性
  158. */
  159. private List<Field> subFields;
  160. /**
  161. * 统计列表
  162. */
  163. private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
  164. /**
  165. * 数字格式
  166. */
  167. private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
  168. /**
  169. * 实体对象
  170. */
  171. public Class<T> clazz;
  172. /**
  173. * 需要排除列属性
  174. */
  175. public String[] excludeFields;
  176. public ExcelUtil(Class<T> clazz)
  177. {
  178. this.clazz = clazz;
  179. }
  180. /**
  181. * 隐藏Excel中列属性
  182. *
  183. * @param fields 列属性名 示例[单个"name"/多个"id","name"]
  184. * @throws Exception
  185. */
  186. public void hideColumn(String... fields)
  187. {
  188. this.excludeFields = fields;
  189. }
  190. public void init(List<T> list, String sheetName, String title, Type type)
  191. {
  192. if (list == null)
  193. {
  194. list = new ArrayList<T>();
  195. }
  196. this.list = list;
  197. this.sheetName = sheetName;
  198. this.type = type;
  199. this.title = title;
  200. createExcelField();
  201. createWorkbook();
  202. createTitle();
  203. createSubHead();
  204. }
  205. /**
  206. * 创建excel第一行标题
  207. */
  208. public void createTitle()
  209. {
  210. if (StringUtils.isNotEmpty(title))
  211. {
  212. subMergedFirstRowNum++;
  213. subMergedLastRowNum++;
  214. int titleLastCol = this.fields.size() - 1;
  215. if (isSubList())
  216. {
  217. titleLastCol = titleLastCol + subFields.size() - 1;
  218. }
  219. Row titleRow = sheet.createRow(rownum == 0 ? rownum++ : 0);
  220. titleRow.setHeightInPoints(30);
  221. Cell titleCell = titleRow.createCell(0);
  222. titleCell.setCellStyle(styles.get("title"));
  223. titleCell.setCellValue(title);
  224. sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), titleLastCol));
  225. }
  226. }
  227. /**
  228. * 创建对象的子列表名称
  229. */
  230. public void createSubHead()
  231. {
  232. if (isSubList())
  233. {
  234. subMergedFirstRowNum++;
  235. subMergedLastRowNum++;
  236. Row subRow = sheet.createRow(rownum);
  237. int excelNum = 0;
  238. for (Object[] objects : fields)
  239. {
  240. Excel attr = (Excel) objects[1];
  241. Cell headCell1 = subRow.createCell(excelNum);
  242. headCell1.setCellValue(attr.name());
  243. headCell1.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
  244. excelNum++;
  245. }
  246. int headFirstRow = excelNum - 1;
  247. int headLastRow = headFirstRow + subFields.size() - 1;
  248. if (headLastRow > headFirstRow)
  249. {
  250. sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, headFirstRow, headLastRow));
  251. }
  252. rownum++;
  253. }
  254. }
  255. /**
  256. * 对excel表单默认第一个索引名转换成list
  257. *
  258. * @param is 输入流
  259. * @return 转换后集合
  260. */
  261. public List<T> importExcel(InputStream is)
  262. {
  263. List<T> list = null;
  264. try
  265. {
  266. list = importExcel(is, 0);
  267. }
  268. catch (Exception e)
  269. {
  270. log.error("导入Excel异常{}", e.getMessage());
  271. throw new UtilException(e.getMessage());
  272. }
  273. finally
  274. {
  275. IOUtils.closeQuietly(is);
  276. }
  277. return list;
  278. }
  279. /**
  280. * 对excel表单默认第一个索引名转换成list
  281. *
  282. * @param is 输入流
  283. * @param titleNum 标题占用行数
  284. * @return 转换后集合
  285. */
  286. public List<T> importExcel(InputStream is, int titleNum) throws Exception
  287. {
  288. return importExcel(StringUtils.EMPTY, is, titleNum);
  289. }
  290. /**
  291. * 对excel表单指定表格索引名转换成list
  292. *
  293. * @param sheetName 表格索引名
  294. * @param titleNum 标题占用行数
  295. * @param is 输入流
  296. * @return 转换后集合
  297. */
  298. public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception
  299. {
  300. this.type = Type.IMPORT;
  301. this.wb = WorkbookFactory.create(is);
  302. List<T> list = new ArrayList<T>();
  303. // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
  304. Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
  305. if (sheet == null)
  306. {
  307. throw new IOException("文件sheet不存在");
  308. }
  309. boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook);
  310. Map<String, PictureData> pictures;
  311. if (isXSSFWorkbook)
  312. {
  313. pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb);
  314. }
  315. else
  316. {
  317. pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb);
  318. }
  319. // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1
  320. int rows = sheet.getLastRowNum();
  321. if (rows > 0)
  322. {
  323. // 定义一个map用于存放excel列的序号和field.
  324. Map<String, Integer> cellMap = new HashMap<String, Integer>();
  325. // 获取表头
  326. Row heard = sheet.getRow(titleNum);
  327. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
  328. {
  329. Cell cell = heard.getCell(i);
  330. if (StringUtils.isNotNull(cell))
  331. {
  332. String value = this.getCellValue(heard, i).toString();
  333. cellMap.put(value, i);
  334. }
  335. else
  336. {
  337. cellMap.put(null, i);
  338. }
  339. }
  340. // 有数据时才处理 得到类的所有field.
  341. List<Object[]> fields = this.getFields();
  342. Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
  343. for (Object[] objects : fields)
  344. {
  345. Excel attr = (Excel) objects[1];
  346. Integer column = cellMap.get(attr.name());
  347. if (column != null)
  348. {
  349. fieldsMap.put(column, objects);
  350. }
  351. }
  352. for (int i = titleNum + 1; i <= rows; i++)
  353. {
  354. // 从第2行开始取数据,默认第一行是表头.
  355. Row row = sheet.getRow(i);
  356. // 判断当前行是否是空行
  357. if (isRowEmpty(row))
  358. {
  359. continue;
  360. }
  361. T entity = null;
  362. for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet())
  363. {
  364. Object val = this.getCellValue(row, entry.getKey());
  365. // 如果不存在实例则新建.
  366. entity = (entity == null ? clazz.newInstance() : entity);
  367. // 从map中得到对应列的field.
  368. Field field = (Field) entry.getValue()[0];
  369. Excel attr = (Excel) entry.getValue()[1];
  370. // 取得类型,并根据对象类型设置值.
  371. Class<?> fieldType = field.getType();
  372. if (String.class == fieldType)
  373. {
  374. String s = Convert.toStr(val);
  375. if (StringUtils.endsWith(s, ".0"))
  376. {
  377. val = StringUtils.substringBefore(s, ".0");
  378. }
  379. else
  380. {
  381. String dateFormat = field.getAnnotation(Excel.class).dateFormat();
  382. if (StringUtils.isNotEmpty(dateFormat))
  383. {
  384. val = parseDateToStr(dateFormat, val);
  385. }
  386. else
  387. {
  388. val = Convert.toStr(val);
  389. }
  390. }
  391. }
  392. else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  393. {
  394. val = Convert.toInt(val);
  395. }
  396. else if ((Long.TYPE == fieldType || Long.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  397. {
  398. val = Convert.toLong(val);
  399. }
  400. else if (Double.TYPE == fieldType || Double.class == fieldType)
  401. {
  402. val = Convert.toDouble(val);
  403. }
  404. else if (Float.TYPE == fieldType || Float.class == fieldType)
  405. {
  406. val = Convert.toFloat(val);
  407. }
  408. else if (BigDecimal.class == fieldType)
  409. {
  410. val = Convert.toBigDecimal(val);
  411. }
  412. else if (Date.class == fieldType)
  413. {
  414. if (val instanceof String)
  415. {
  416. val = DateUtils.parseDate(val);
  417. }
  418. else if (val instanceof Double)
  419. {
  420. val = DateUtil.getJavaDate((Double) val);
  421. }
  422. }
  423. else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
  424. {
  425. val = Convert.toBool(val, false);
  426. }
  427. if (StringUtils.isNotNull(fieldType))
  428. {
  429. String propertyName = field.getName();
  430. if (StringUtils.isNotEmpty(attr.targetAttr()))
  431. {
  432. propertyName = field.getName() + "." + attr.targetAttr();
  433. }
  434. if (StringUtils.isNotEmpty(attr.readConverterExp()))
  435. {
  436. val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
  437. }
  438. else if (StringUtils.isNotEmpty(attr.dictType()))
  439. {
  440. val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
  441. }
  442. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  443. {
  444. val = dataFormatHandlerAdapter(val, attr, null);
  445. }
  446. else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures))
  447. {
  448. PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
  449. if (image == null)
  450. {
  451. val = "";
  452. }
  453. else
  454. {
  455. byte[] data = image.getData();
  456. val = FileUtils.writeImportBytes(data);
  457. }
  458. }
  459. ReflectUtils.invokeSetter(entity, propertyName, val);
  460. }
  461. }
  462. list.add(entity);
  463. }
  464. }
  465. return list;
  466. }
  467. /**
  468. * 对list数据源将其里面的数据导入到excel表单
  469. *
  470. * @param list 导出数据集合
  471. * @param sheetName 工作表的名称
  472. * @return 结果
  473. */
  474. public AjaxResult exportExcel(List<T> list, String sheetName)
  475. {
  476. return exportExcel(list, sheetName, StringUtils.EMPTY);
  477. }
  478. /**
  479. * 对list数据源将其里面的数据导入到excel表单
  480. *
  481. * @param list 导出数据集合
  482. * @param sheetName 工作表的名称
  483. * @param title 标题
  484. * @return 结果
  485. */
  486. public AjaxResult exportExcel(List<T> list, String sheetName, String title)
  487. {
  488. this.init(list, sheetName, title, Type.EXPORT);
  489. return exportExcel();
  490. }
  491. /**
  492. * 对list数据源将其里面的数据导入到excel表单
  493. *
  494. * @param response 返回数据
  495. * @param list 导出数据集合
  496. * @param sheetName 工作表的名称
  497. * @return 结果
  498. */
  499. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName)
  500. {
  501. exportExcel(response, list, sheetName, StringUtils.EMPTY);
  502. }
  503. /**
  504. * 对list数据源将其里面的数据导入到excel表单
  505. *
  506. * @param response 返回数据
  507. * @param list 导出数据集合
  508. * @param sheetName 工作表的名称
  509. * @param title 标题
  510. * @return 结果
  511. */
  512. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String title)
  513. {
  514. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  515. response.setCharacterEncoding("utf-8");
  516. this.init(list, sheetName, title, Type.EXPORT);
  517. exportExcel(response);
  518. }
  519. /**
  520. * 对list数据源将其里面的数据导入到excel表单
  521. *
  522. * @param sheetName 工作表的名称
  523. * @return 结果
  524. */
  525. public AjaxResult importTemplateExcel(String sheetName)
  526. {
  527. return importTemplateExcel(sheetName, StringUtils.EMPTY);
  528. }
  529. /**
  530. * 对list数据源将其里面的数据导入到excel表单
  531. *
  532. * @param sheetName 工作表的名称
  533. * @param title 标题
  534. * @return 结果
  535. */
  536. public AjaxResult importTemplateExcel(String sheetName, String title)
  537. {
  538. this.init(null, sheetName, title, Type.IMPORT);
  539. return exportExcel();
  540. }
  541. /**
  542. * 对list数据源将其里面的数据导入到excel表单
  543. *
  544. * @param sheetName 工作表的名称
  545. * @return 结果
  546. */
  547. public void importTemplateExcel(HttpServletResponse response, String sheetName)
  548. {
  549. importTemplateExcel(response, sheetName, StringUtils.EMPTY);
  550. }
  551. /**
  552. * 对list数据源将其里面的数据导入到excel表单
  553. *
  554. * @param sheetName 工作表的名称
  555. * @param title 标题
  556. * @return 结果
  557. */
  558. public void importTemplateExcel(HttpServletResponse response, String sheetName, String title)
  559. {
  560. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  561. response.setCharacterEncoding("utf-8");
  562. this.init(null, sheetName, title, Type.IMPORT);
  563. exportExcel(response);
  564. }
  565. /**
  566. * 对list数据源将其里面的数据导入到excel表单
  567. *
  568. * @return 结果
  569. */
  570. public void exportExcel(HttpServletResponse response)
  571. {
  572. try
  573. {
  574. writeSheet();
  575. wb.write(response.getOutputStream());
  576. }
  577. catch (Exception e)
  578. {
  579. log.error("导出Excel异常{}", e.getMessage());
  580. }
  581. finally
  582. {
  583. IOUtils.closeQuietly(wb);
  584. }
  585. }
  586. /**
  587. * 对list数据源将其里面的数据导入到excel表单
  588. *
  589. * @return 结果
  590. */
  591. public AjaxResult exportExcel()
  592. {
  593. OutputStream out = null;
  594. try
  595. {
  596. writeSheet();
  597. String filename = encodingFilename(sheetName);
  598. out = new FileOutputStream(getAbsoluteFile(filename));
  599. wb.write(out);
  600. return AjaxResult.success(filename);
  601. }
  602. catch (Exception e)
  603. {
  604. log.error("导出Excel异常{}", e.getMessage());
  605. throw new UtilException("导出Excel失败,请联系网站管理员!");
  606. }
  607. finally
  608. {
  609. IOUtils.closeQuietly(wb);
  610. IOUtils.closeQuietly(out);
  611. }
  612. }
  613. /**
  614. * 创建写入数据到Sheet
  615. */
  616. public void writeSheet()
  617. {
  618. // 取出一共有多少个sheet.
  619. int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
  620. for (int index = 0; index < sheetNo; index++)
  621. {
  622. createSheet(sheetNo, index);
  623. // 产生一行
  624. Row row = sheet.createRow(rownum);
  625. int column = 0;
  626. // 写入各个字段的列头名称
  627. for (Object[] os : fields)
  628. {
  629. Field field = (Field) os[0];
  630. Excel excel = (Excel) os[1];
  631. if (Collection.class.isAssignableFrom(field.getType()))
  632. {
  633. for (Field subField : subFields)
  634. {
  635. Excel subExcel = subField.getAnnotation(Excel.class);
  636. this.createHeadCell(subExcel, row, column++);
  637. }
  638. }
  639. else
  640. {
  641. this.createHeadCell(excel, row, column++);
  642. }
  643. }
  644. if (Type.EXPORT.equals(type))
  645. {
  646. fillExcelData(index, row);
  647. addStatisticsRow();
  648. }
  649. }
  650. }
  651. /**
  652. * 填充excel数据
  653. *
  654. * @param index 序号
  655. * @param row 单元格行
  656. */
  657. @SuppressWarnings("unchecked")
  658. public void fillExcelData(int index, Row row)
  659. {
  660. int startNo = index * sheetSize;
  661. int endNo = Math.min(startNo + sheetSize, list.size());
  662. int rowNo = (1 + rownum) - startNo;
  663. for (int i = startNo; i < endNo; i++)
  664. {
  665. rowNo = isSubList() ? (i > 1 ? rowNo + 1 : rowNo + i) : i + 1 + rownum - startNo;
  666. row = sheet.createRow(rowNo);
  667. // 得到导出对象.
  668. T vo = (T) list.get(i);
  669. Collection<?> subList = null;
  670. if (isSubList())
  671. {
  672. if (isSubListValue(vo))
  673. {
  674. subList = getListCellValue(vo);
  675. subMergedLastRowNum = subMergedLastRowNum + subList.size();
  676. }
  677. else
  678. {
  679. subMergedFirstRowNum++;
  680. subMergedLastRowNum++;
  681. }
  682. }
  683. int column = 0;
  684. for (Object[] os : fields)
  685. {
  686. Field field = (Field) os[0];
  687. Excel excel = (Excel) os[1];
  688. if (Collection.class.isAssignableFrom(field.getType()) && StringUtils.isNotNull(subList))
  689. {
  690. boolean subFirst = false;
  691. for (Object obj : subList)
  692. {
  693. if (subFirst)
  694. {
  695. rowNo++;
  696. row = sheet.createRow(rowNo);
  697. }
  698. List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Excel.class);
  699. int subIndex = 0;
  700. for (Field subField : subFields)
  701. {
  702. if (subField.isAnnotationPresent(Excel.class))
  703. {
  704. subField.setAccessible(true);
  705. Excel attr = subField.getAnnotation(Excel.class);
  706. this.addCell(attr, row, (T) obj, subField, column + subIndex);
  707. }
  708. subIndex++;
  709. }
  710. subFirst = true;
  711. }
  712. this.subMergedFirstRowNum = this.subMergedFirstRowNum + subList.size();
  713. }
  714. else
  715. {
  716. this.addCell(excel, row, vo, field, column++);
  717. }
  718. }
  719. }
  720. }
  721. /**
  722. * 创建表格样式
  723. *
  724. * @param wb 工作薄对象
  725. * @return 样式列表
  726. */
  727. private Map<String, CellStyle> createStyles(Workbook wb)
  728. {
  729. // 写入各条记录,每条记录对应excel表中的一行
  730. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  731. CellStyle style = wb.createCellStyle();
  732. style.setAlignment(HorizontalAlignment.CENTER);
  733. style.setVerticalAlignment(VerticalAlignment.CENTER);
  734. Font titleFont = wb.createFont();
  735. titleFont.setFontName("Arial");
  736. titleFont.setFontHeightInPoints((short) 16);
  737. titleFont.setBold(true);
  738. style.setFont(titleFont);
  739. styles.put("title", style);
  740. style = wb.createCellStyle();
  741. style.setAlignment(HorizontalAlignment.CENTER);
  742. style.setVerticalAlignment(VerticalAlignment.CENTER);
  743. style.setBorderRight(BorderStyle.THIN);
  744. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  745. style.setBorderLeft(BorderStyle.THIN);
  746. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  747. style.setBorderTop(BorderStyle.THIN);
  748. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  749. style.setBorderBottom(BorderStyle.THIN);
  750. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  751. Font dataFont = wb.createFont();
  752. dataFont.setFontName("Arial");
  753. dataFont.setFontHeightInPoints((short) 10);
  754. style.setFont(dataFont);
  755. styles.put("data", style);
  756. style = wb.createCellStyle();
  757. style.setAlignment(HorizontalAlignment.CENTER);
  758. style.setVerticalAlignment(VerticalAlignment.CENTER);
  759. Font totalFont = wb.createFont();
  760. totalFont.setFontName("Arial");
  761. totalFont.setFontHeightInPoints((short) 10);
  762. style.setFont(totalFont);
  763. styles.put("total", style);
  764. styles.putAll(annotationHeaderStyles(wb, styles));
  765. styles.putAll(annotationDataStyles(wb));
  766. return styles;
  767. }
  768. /**
  769. * 根据Excel注解创建表格头样式
  770. *
  771. * @param wb 工作薄对象
  772. * @return 自定义样式列表
  773. */
  774. private Map<String, CellStyle> annotationHeaderStyles(Workbook wb, Map<String, CellStyle> styles)
  775. {
  776. Map<String, CellStyle> headerStyles = new HashMap<String, CellStyle>();
  777. for (Object[] os : fields)
  778. {
  779. Excel excel = (Excel) os[1];
  780. String key = StringUtils.format("header_{}_{}", excel.headerColor(), excel.headerBackgroundColor());
  781. if (!headerStyles.containsKey(key))
  782. {
  783. CellStyle style = wb.createCellStyle();
  784. style.cloneStyleFrom(styles.get("data"));
  785. style.setAlignment(HorizontalAlignment.CENTER);
  786. style.setVerticalAlignment(VerticalAlignment.CENTER);
  787. style.setFillForegroundColor(excel.headerBackgroundColor().index);
  788. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  789. Font headerFont = wb.createFont();
  790. headerFont.setFontName("Arial");
  791. headerFont.setFontHeightInPoints((short) 10);
  792. headerFont.setBold(true);
  793. headerFont.setColor(excel.headerColor().index);
  794. style.setFont(headerFont);
  795. headerStyles.put(key, style);
  796. }
  797. }
  798. return headerStyles;
  799. }
  800. /**
  801. * 根据Excel注解创建表格列样式
  802. *
  803. * @param wb 工作薄对象
  804. * @return 自定义样式列表
  805. */
  806. private Map<String, CellStyle> annotationDataStyles(Workbook wb)
  807. {
  808. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  809. for (Object[] os : fields)
  810. {
  811. Excel excel = (Excel) os[1];
  812. String key = StringUtils.format("data_{}_{}_{}", excel.align(), excel.color(), excel.backgroundColor());
  813. if (!styles.containsKey(key))
  814. {
  815. CellStyle style = wb.createCellStyle();
  816. style.setAlignment(excel.align());
  817. style.setVerticalAlignment(VerticalAlignment.CENTER);
  818. style.setBorderRight(BorderStyle.THIN);
  819. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  820. style.setBorderLeft(BorderStyle.THIN);
  821. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  822. style.setBorderTop(BorderStyle.THIN);
  823. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  824. style.setBorderBottom(BorderStyle.THIN);
  825. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  826. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  827. style.setFillForegroundColor(excel.backgroundColor().getIndex());
  828. Font dataFont = wb.createFont();
  829. dataFont.setFontName("Arial");
  830. dataFont.setFontHeightInPoints((short) 10);
  831. dataFont.setColor(excel.color().index);
  832. style.setFont(dataFont);
  833. styles.put(key, style);
  834. }
  835. }
  836. return styles;
  837. }
  838. /**
  839. * 创建单元格
  840. */
  841. public Cell createHeadCell(Excel attr, Row row, int column)
  842. {
  843. // 创建列
  844. Cell cell = row.createCell(column);
  845. // 写入列信息
  846. cell.setCellValue(attr.name());
  847. setDataValidation(attr, row, column);
  848. cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
  849. if (isSubList())
  850. {
  851. // 填充默认样式,防止合并单元格样式失效
  852. sheet.setDefaultColumnStyle(column, styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
  853. if (attr.needMerge())
  854. {
  855. sheet.addMergedRegion(new CellRangeAddress(rownum - 1, rownum, column, column));
  856. }
  857. }
  858. return cell;
  859. }
  860. /**
  861. * 设置单元格信息
  862. *
  863. * @param value 单元格值
  864. * @param attr 注解相关
  865. * @param cell 单元格信息
  866. */
  867. public void setCellVo(Object value, Excel attr, Cell cell)
  868. {
  869. if (ColumnType.STRING == attr.cellType())
  870. {
  871. String cellValue = Convert.toStr(value);
  872. // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。
  873. if (StringUtils.startsWithAny(cellValue, FORMULA_STR))
  874. {
  875. cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
  876. }
  877. if (value instanceof Collection && StringUtils.equals("[]", cellValue))
  878. {
  879. cellValue = StringUtils.EMPTY;
  880. }
  881. cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix());
  882. }
  883. else if (ColumnType.NUMERIC == attr.cellType())
  884. {
  885. if (StringUtils.isNotNull(value))
  886. {
  887. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  888. }
  889. }
  890. else if (ColumnType.IMAGE == attr.cellType())
  891. {
  892. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  893. String imagePath = Convert.toStr(value);
  894. if (StringUtils.isNotEmpty(imagePath))
  895. {
  896. byte[] data = ImageUtils.getImage(imagePath);
  897. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  898. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  899. }
  900. }
  901. }
  902. /**
  903. * 获取画布
  904. */
  905. public static Drawing<?> getDrawingPatriarch(Sheet sheet)
  906. {
  907. if (sheet.getDrawingPatriarch() == null)
  908. {
  909. sheet.createDrawingPatriarch();
  910. }
  911. return sheet.getDrawingPatriarch();
  912. }
  913. /**
  914. * 获取图片类型,设置图片插入类型
  915. */
  916. public int getImageType(byte[] value)
  917. {
  918. String type = FileTypeUtils.getFileExtendName(value);
  919. if ("JPG".equalsIgnoreCase(type))
  920. {
  921. return Workbook.PICTURE_TYPE_JPEG;
  922. }
  923. else if ("PNG".equalsIgnoreCase(type))
  924. {
  925. return Workbook.PICTURE_TYPE_PNG;
  926. }
  927. return Workbook.PICTURE_TYPE_JPEG;
  928. }
  929. /**
  930. * 创建表格样式
  931. */
  932. public void setDataValidation(Excel attr, Row row, int column)
  933. {
  934. if (attr.name().indexOf("注:") >= 0)
  935. {
  936. sheet.setColumnWidth(column, 6000);
  937. }
  938. else
  939. {
  940. // 设置列宽
  941. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  942. }
  943. if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0)
  944. {
  945. if (attr.combo().length > 15 || StringUtils.join(attr.combo()).length() > 255)
  946. {
  947. // 如果下拉数大于15或字符串长度大于255,则使用一个新sheet存储,避免生成的模板下拉值获取不到
  948. setXSSFValidationWithHidden(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  949. }
  950. else
  951. {
  952. // 提示信息或只能选择不能输入的列内容.
  953. setPromptOrValidation(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  954. }
  955. }
  956. }
  957. /**
  958. * 添加单元格
  959. */
  960. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  961. {
  962. Cell cell = null;
  963. try
  964. {
  965. // 设置行高
  966. row.setHeight(maxHeight);
  967. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  968. if (attr.isExport())
  969. {
  970. // 创建cell
  971. cell = row.createCell(column);
  972. if (isSubListValue(vo) && getListCellValue(vo).size() > 1 && attr.needMerge())
  973. {
  974. CellRangeAddress cellAddress = new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column);
  975. sheet.addMergedRegion(cellAddress);
  976. }
  977. cell.setCellStyle(styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
  978. // 用于读取对象中的属性
  979. Object value = getTargetValue(vo, field, attr);
  980. String dateFormat = attr.dateFormat();
  981. String readConverterExp = attr.readConverterExp();
  982. String separator = attr.separator();
  983. String dictType = attr.dictType();
  984. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  985. {
  986. cell.setCellValue(parseDateToStr(dateFormat, value));
  987. }
  988. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  989. {
  990. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  991. }
  992. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  993. {
  994. if (!sysDictMap.containsKey(dictType + value))
  995. {
  996. String lable = convertDictByExp(Convert.toStr(value), dictType, separator);
  997. sysDictMap.put(dictType + value, lable);
  998. }
  999. cell.setCellValue(sysDictMap.get(dictType + value));
  1000. }
  1001. else if (value instanceof BigDecimal && -1 != attr.scale())
  1002. {
  1003. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).doubleValue());
  1004. }
  1005. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  1006. {
  1007. cell.setCellValue(dataFormatHandlerAdapter(value, attr, cell));
  1008. }
  1009. else
  1010. {
  1011. // 设置列类型
  1012. setCellVo(value, attr, cell);
  1013. }
  1014. addStatisticsData(column, Convert.toStr(value), attr);
  1015. }
  1016. }
  1017. catch (Exception e)
  1018. {
  1019. log.error("导出Excel失败{}", e);
  1020. }
  1021. return cell;
  1022. }
  1023. /**
  1024. * 设置 POI XSSFSheet 单元格提示或选择框
  1025. *
  1026. * @param sheet 表单
  1027. * @param textlist 下拉框显示的内容
  1028. * @param promptContent 提示内容
  1029. * @param firstRow 开始行
  1030. * @param endRow 结束行
  1031. * @param firstCol 开始列
  1032. * @param endCol 结束列
  1033. */
  1034. public void setPromptOrValidation(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow,
  1035. int firstCol, int endCol)
  1036. {
  1037. DataValidationHelper helper = sheet.getDataValidationHelper();
  1038. DataValidationConstraint constraint = textlist.length > 0 ? helper.createExplicitListConstraint(textlist) : helper.createCustomConstraint("DD1");
  1039. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  1040. DataValidation dataValidation = helper.createValidation(constraint, regions);
  1041. if (StringUtils.isNotEmpty(promptContent))
  1042. {
  1043. // 如果设置了提示信息则鼠标放上去提示
  1044. dataValidation.createPromptBox("", promptContent);
  1045. dataValidation.setShowPromptBox(true);
  1046. }
  1047. // 处理Excel兼容性问题
  1048. if (dataValidation instanceof XSSFDataValidation)
  1049. {
  1050. dataValidation.setSuppressDropDownArrow(true);
  1051. dataValidation.setShowErrorBox(true);
  1052. }
  1053. else
  1054. {
  1055. dataValidation.setSuppressDropDownArrow(false);
  1056. }
  1057. sheet.addValidationData(dataValidation);
  1058. }
  1059. /**
  1060. * 设置某些列的值只能输入预制的数据,显示下拉框(兼容超出一定数量的下拉框).
  1061. *
  1062. * @param sheet 要设置的sheet.
  1063. * @param textlist 下拉框显示的内容
  1064. * @param promptContent 提示内容
  1065. * @param firstRow 开始行
  1066. * @param endRow 结束行
  1067. * @param firstCol 开始列
  1068. * @param endCol 结束列
  1069. */
  1070. public void setXSSFValidationWithHidden(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow, int firstCol, int endCol)
  1071. {
  1072. String hideSheetName = "combo_" + firstCol + "_" + endCol;
  1073. Sheet hideSheet = wb.createSheet(hideSheetName); // 用于存储 下拉菜单数据
  1074. for (int i = 0; i < textlist.length; i++)
  1075. {
  1076. hideSheet.createRow(i).createCell(0).setCellValue(textlist[i]);
  1077. }
  1078. // 创建名称,可被其他单元格引用
  1079. Name name = wb.createName();
  1080. name.setNameName(hideSheetName + "_data");
  1081. name.setRefersToFormula(hideSheetName + "!$A$1:$A$" + textlist.length);
  1082. DataValidationHelper helper = sheet.getDataValidationHelper();
  1083. // 加载下拉列表内容
  1084. DataValidationConstraint constraint = helper.createFormulaListConstraint(hideSheetName + "_data");
  1085. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  1086. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  1087. // 数据有效性对象
  1088. DataValidation dataValidation = helper.createValidation(constraint, regions);
  1089. if (StringUtils.isNotEmpty(promptContent))
  1090. {
  1091. // 如果设置了提示信息则鼠标放上去提示
  1092. dataValidation.createPromptBox("", promptContent);
  1093. dataValidation.setShowPromptBox(true);
  1094. }
  1095. // 处理Excel兼容性问题
  1096. if (dataValidation instanceof XSSFDataValidation)
  1097. {
  1098. dataValidation.setSuppressDropDownArrow(true);
  1099. dataValidation.setShowErrorBox(true);
  1100. }
  1101. else
  1102. {
  1103. dataValidation.setSuppressDropDownArrow(false);
  1104. }
  1105. sheet.addValidationData(dataValidation);
  1106. // 设置hiddenSheet隐藏
  1107. wb.setSheetHidden(wb.getSheetIndex(hideSheet), true);
  1108. }
  1109. /**
  1110. * 解析导出值 0=男,1=女,2=未知
  1111. *
  1112. * @param propertyValue 参数值
  1113. * @param converterExp 翻译注解
  1114. * @param separator 分隔符
  1115. * @return 解析后值
  1116. */
  1117. public static String convertByExp(String propertyValue, String converterExp, String separator)
  1118. {
  1119. StringBuilder propertyString = new StringBuilder();
  1120. String[] convertSource = converterExp.split(",");
  1121. for (String item : convertSource)
  1122. {
  1123. String[] itemArray = item.split("=");
  1124. if (StringUtils.containsAny(propertyValue, separator))
  1125. {
  1126. for (String value : propertyValue.split(separator))
  1127. {
  1128. if (itemArray[0].equals(value))
  1129. {
  1130. propertyString.append(itemArray[1] + separator);
  1131. break;
  1132. }
  1133. }
  1134. }
  1135. else
  1136. {
  1137. if (itemArray[0].equals(propertyValue))
  1138. {
  1139. return itemArray[1];
  1140. }
  1141. }
  1142. }
  1143. return StringUtils.stripEnd(propertyString.toString(), separator);
  1144. }
  1145. /**
  1146. * 反向解析值 男=0,女=1,未知=2
  1147. *
  1148. * @param propertyValue 参数值
  1149. * @param converterExp 翻译注解
  1150. * @param separator 分隔符
  1151. * @return 解析后值
  1152. */
  1153. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  1154. {
  1155. StringBuilder propertyString = new StringBuilder();
  1156. String[] convertSource = converterExp.split(",");
  1157. for (String item : convertSource)
  1158. {
  1159. String[] itemArray = item.split("=");
  1160. if (StringUtils.containsAny(propertyValue, separator))
  1161. {
  1162. for (String value : propertyValue.split(separator))
  1163. {
  1164. if (itemArray[1].equals(value))
  1165. {
  1166. propertyString.append(itemArray[0] + separator);
  1167. break;
  1168. }
  1169. }
  1170. }
  1171. else
  1172. {
  1173. if (itemArray[1].equals(propertyValue))
  1174. {
  1175. return itemArray[0];
  1176. }
  1177. }
  1178. }
  1179. return StringUtils.stripEnd(propertyString.toString(), separator);
  1180. }
  1181. /**
  1182. * 解析字典值
  1183. *
  1184. * @param dictValue 字典值
  1185. * @param dictType 字典类型
  1186. * @param separator 分隔符
  1187. * @return 字典标签
  1188. */
  1189. public static String convertDictByExp(String dictValue, String dictType, String separator)
  1190. {
  1191. return DictUtils.getDictLabel(dictType, dictValue, separator);
  1192. }
  1193. /**
  1194. * 反向解析值字典值
  1195. *
  1196. * @param dictLabel 字典标签
  1197. * @param dictType 字典类型
  1198. * @param separator 分隔符
  1199. * @return 字典值
  1200. */
  1201. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  1202. {
  1203. return DictUtils.getDictValue(dictType, dictLabel, separator);
  1204. }
  1205. /**
  1206. * 数据处理器
  1207. *
  1208. * @param value 数据值
  1209. * @param excel 数据注解
  1210. * @return
  1211. */
  1212. public String dataFormatHandlerAdapter(Object value, Excel excel, Cell cell)
  1213. {
  1214. try
  1215. {
  1216. Object instance = excel.handler().newInstance();
  1217. Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class, Cell.class, Workbook.class });
  1218. value = formatMethod.invoke(instance, value, excel.args(), cell, this.wb);
  1219. }
  1220. catch (Exception e)
  1221. {
  1222. log.error("不能格式化数据 " + excel.handler(), e.getMessage());
  1223. }
  1224. return Convert.toStr(value);
  1225. }
  1226. /**
  1227. * 合计统计信息
  1228. */
  1229. private void addStatisticsData(Integer index, String text, Excel entity)
  1230. {
  1231. if (entity != null && entity.isStatistics())
  1232. {
  1233. Double temp = 0D;
  1234. if (!statistics.containsKey(index))
  1235. {
  1236. statistics.put(index, temp);
  1237. }
  1238. try
  1239. {
  1240. temp = Double.valueOf(text);
  1241. }
  1242. catch (NumberFormatException e)
  1243. {
  1244. }
  1245. statistics.put(index, statistics.get(index) + temp);
  1246. }
  1247. }
  1248. /**
  1249. * 创建统计行
  1250. */
  1251. public void addStatisticsRow()
  1252. {
  1253. if (statistics.size() > 0)
  1254. {
  1255. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  1256. Set<Integer> keys = statistics.keySet();
  1257. Cell cell = row.createCell(0);
  1258. cell.setCellStyle(styles.get("total"));
  1259. cell.setCellValue("合计");
  1260. for (Integer key : keys)
  1261. {
  1262. cell = row.createCell(key);
  1263. cell.setCellStyle(styles.get("total"));
  1264. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  1265. }
  1266. statistics.clear();
  1267. }
  1268. }
  1269. /**
  1270. * 编码文件名
  1271. */
  1272. public String encodingFilename(String filename)
  1273. {
  1274. filename = UUID.randomUUID() + "_" + filename + ".xlsx";
  1275. return filename;
  1276. }
  1277. /**
  1278. * 获取下载路径
  1279. *
  1280. * @param filename 文件名称
  1281. */
  1282. public String getAbsoluteFile(String filename)
  1283. {
  1284. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  1285. File desc = new File(downloadPath);
  1286. if (!desc.getParentFile().exists())
  1287. {
  1288. desc.getParentFile().mkdirs();
  1289. }
  1290. return downloadPath;
  1291. }
  1292. /**
  1293. * 获取bean中的属性值
  1294. *
  1295. * @param vo 实体对象
  1296. * @param field 字段
  1297. * @param excel 注解
  1298. * @return 最终的属性值
  1299. * @throws Exception
  1300. */
  1301. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  1302. {
  1303. Object o = field.get(vo);
  1304. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1305. {
  1306. String target = excel.targetAttr();
  1307. if (target.contains("."))
  1308. {
  1309. String[] targets = target.split("[.]");
  1310. for (String name : targets)
  1311. {
  1312. o = getValue(o, name);
  1313. }
  1314. }
  1315. else
  1316. {
  1317. o = getValue(o, target);
  1318. }
  1319. }
  1320. return o;
  1321. }
  1322. /**
  1323. * 以类的属性的get方法方法形式获取值
  1324. *
  1325. * @param o
  1326. * @param name
  1327. * @return value
  1328. * @throws Exception
  1329. */
  1330. private Object getValue(Object o, String name) throws Exception
  1331. {
  1332. if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
  1333. {
  1334. Class<?> clazz = o.getClass();
  1335. Field field = clazz.getDeclaredField(name);
  1336. field.setAccessible(true);
  1337. o = field.get(o);
  1338. }
  1339. return o;
  1340. }
  1341. /**
  1342. * 得到所有定义字段
  1343. */
  1344. private void createExcelField()
  1345. {
  1346. this.fields = getFields();
  1347. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  1348. this.maxHeight = getRowHeight();
  1349. }
  1350. /**
  1351. * 获取字段注解信息
  1352. */
  1353. public List<Object[]> getFields()
  1354. {
  1355. List<Object[]> fields = new ArrayList<Object[]>();
  1356. List<Field> tempFields = new ArrayList<>();
  1357. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1358. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1359. for (Field field : tempFields)
  1360. {
  1361. if (!ArrayUtils.contains(this.excludeFields, field.getName()))
  1362. {
  1363. // 单注解
  1364. if (field.isAnnotationPresent(Excel.class))
  1365. {
  1366. Excel attr = field.getAnnotation(Excel.class);
  1367. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1368. {
  1369. field.setAccessible(true);
  1370. fields.add(new Object[] { field, attr });
  1371. }
  1372. if (Collection.class.isAssignableFrom(field.getType()))
  1373. {
  1374. subMethod = getSubMethod(field.getName(), clazz);
  1375. ParameterizedType pt = (ParameterizedType) field.getGenericType();
  1376. Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0];
  1377. this.subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class);
  1378. }
  1379. }
  1380. // 多注解
  1381. if (field.isAnnotationPresent(Excels.class))
  1382. {
  1383. Excels attrs = field.getAnnotation(Excels.class);
  1384. Excel[] excels = attrs.value();
  1385. for (Excel attr : excels)
  1386. {
  1387. if (!ArrayUtils.contains(this.excludeFields, field.getName() + "." + attr.targetAttr())
  1388. && (attr != null && (attr.type() == Type.ALL || attr.type() == type)))
  1389. {
  1390. field.setAccessible(true);
  1391. fields.add(new Object[] { field, attr });
  1392. }
  1393. }
  1394. }
  1395. }
  1396. }
  1397. return fields;
  1398. }
  1399. /**
  1400. * 根据注解获取最大行高
  1401. */
  1402. public short getRowHeight()
  1403. {
  1404. double maxHeight = 0;
  1405. for (Object[] os : this.fields)
  1406. {
  1407. Excel excel = (Excel) os[1];
  1408. maxHeight = Math.max(maxHeight, excel.height());
  1409. }
  1410. return (short) (maxHeight * 20);
  1411. }
  1412. /**
  1413. * 创建一个工作簿
  1414. */
  1415. public void createWorkbook()
  1416. {
  1417. this.wb = new SXSSFWorkbook(500);
  1418. this.sheet = wb.createSheet();
  1419. wb.setSheetName(0, sheetName);
  1420. this.styles = createStyles(wb);
  1421. }
  1422. /**
  1423. * 创建工作表
  1424. *
  1425. * @param sheetNo sheet数量
  1426. * @param index 序号
  1427. */
  1428. public void createSheet(int sheetNo, int index)
  1429. {
  1430. // 设置工作表的名称.
  1431. if (sheetNo > 1 && index > 0)
  1432. {
  1433. this.sheet = wb.createSheet();
  1434. this.createTitle();
  1435. wb.setSheetName(index, sheetName + index);
  1436. }
  1437. }
  1438. /**
  1439. * 获取单元格值
  1440. *
  1441. * @param row 获取的行
  1442. * @param column 获取单元格列号
  1443. * @return 单元格值
  1444. */
  1445. public Object getCellValue(Row row, int column)
  1446. {
  1447. if (row == null)
  1448. {
  1449. return row;
  1450. }
  1451. Object val = "";
  1452. try
  1453. {
  1454. Cell cell = row.getCell(column);
  1455. if (StringUtils.isNotNull(cell))
  1456. {
  1457. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1458. {
  1459. val = cell.getNumericCellValue();
  1460. if (DateUtil.isCellDateFormatted(cell))
  1461. {
  1462. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1463. }
  1464. else
  1465. {
  1466. if ((Double) val % 1 != 0)
  1467. {
  1468. val = new BigDecimal(val.toString());
  1469. }
  1470. else
  1471. {
  1472. val = new DecimalFormat("0").format(val);
  1473. }
  1474. }
  1475. }
  1476. else if (cell.getCellType() == CellType.STRING)
  1477. {
  1478. val = cell.getStringCellValue();
  1479. }
  1480. else if (cell.getCellType() == CellType.BOOLEAN)
  1481. {
  1482. val = cell.getBooleanCellValue();
  1483. }
  1484. else if (cell.getCellType() == CellType.ERROR)
  1485. {
  1486. val = cell.getErrorCellValue();
  1487. }
  1488. }
  1489. }
  1490. catch (Exception e)
  1491. {
  1492. return val;
  1493. }
  1494. return val;
  1495. }
  1496. /**
  1497. * 判断是否是空行
  1498. *
  1499. * @param row 判断的行
  1500. * @return
  1501. */
  1502. private boolean isRowEmpty(Row row)
  1503. {
  1504. if (row == null)
  1505. {
  1506. return true;
  1507. }
  1508. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
  1509. {
  1510. Cell cell = row.getCell(i);
  1511. if (cell != null && cell.getCellType() != CellType.BLANK)
  1512. {
  1513. return false;
  1514. }
  1515. }
  1516. return true;
  1517. }
  1518. /**
  1519. * 获取Excel2003图片
  1520. *
  1521. * @param sheet 当前sheet对象
  1522. * @param workbook 工作簿对象
  1523. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1524. */
  1525. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
  1526. {
  1527. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1528. List<HSSFPictureData> pictures = workbook.getAllPictures();
  1529. if (!pictures.isEmpty())
  1530. {
  1531. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
  1532. {
  1533. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
  1534. if (shape instanceof HSSFPicture)
  1535. {
  1536. HSSFPicture pic = (HSSFPicture) shape;
  1537. int pictureIndex = pic.getPictureIndex() - 1;
  1538. HSSFPictureData picData = pictures.get(pictureIndex);
  1539. String picIndex = anchor.getRow1() + "_" + anchor.getCol1();
  1540. sheetIndexPicMap.put(picIndex, picData);
  1541. }
  1542. }
  1543. return sheetIndexPicMap;
  1544. }
  1545. else
  1546. {
  1547. return sheetIndexPicMap;
  1548. }
  1549. }
  1550. /**
  1551. * 获取Excel2007图片
  1552. *
  1553. * @param sheet 当前sheet对象
  1554. * @param workbook 工作簿对象
  1555. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1556. */
  1557. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
  1558. {
  1559. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1560. for (POIXMLDocumentPart dr : sheet.getRelations())
  1561. {
  1562. if (dr instanceof XSSFDrawing)
  1563. {
  1564. XSSFDrawing drawing = (XSSFDrawing) dr;
  1565. List<XSSFShape> shapes = drawing.getShapes();
  1566. for (XSSFShape shape : shapes)
  1567. {
  1568. if (shape instanceof XSSFPicture)
  1569. {
  1570. XSSFPicture pic = (XSSFPicture) shape;
  1571. XSSFClientAnchor anchor = pic.getPreferredSize();
  1572. CTMarker ctMarker = anchor.getFrom();
  1573. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
  1574. sheetIndexPicMap.put(picIndex, pic.getPictureData());
  1575. }
  1576. }
  1577. }
  1578. }
  1579. return sheetIndexPicMap;
  1580. }
  1581. /**
  1582. * 格式化不同类型的日期对象
  1583. *
  1584. * @param dateFormat 日期格式
  1585. * @param val 被格式化的日期对象
  1586. * @return 格式化后的日期字符
  1587. */
  1588. public String parseDateToStr(String dateFormat, Object val)
  1589. {
  1590. if (val == null)
  1591. {
  1592. return "";
  1593. }
  1594. String str;
  1595. if (val instanceof Date)
  1596. {
  1597. str = DateUtils.parseDateToStr(dateFormat, (Date) val);
  1598. }
  1599. else if (val instanceof LocalDateTime)
  1600. {
  1601. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDateTime) val));
  1602. }
  1603. else if (val instanceof LocalDate)
  1604. {
  1605. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val));
  1606. }
  1607. else
  1608. {
  1609. str = val.toString();
  1610. }
  1611. return str;
  1612. }
  1613. /**
  1614. * 是否有对象的子列表
  1615. */
  1616. public boolean isSubList()
  1617. {
  1618. return StringUtils.isNotNull(subFields) && subFields.size() > 0;
  1619. }
  1620. /**
  1621. * 是否有对象的子列表,集合不为空
  1622. */
  1623. public boolean isSubListValue(T vo)
  1624. {
  1625. return StringUtils.isNotNull(subFields) && subFields.size() > 0 && StringUtils.isNotNull(getListCellValue(vo)) && getListCellValue(vo).size() > 0;
  1626. }
  1627. /**
  1628. * 获取集合的值
  1629. */
  1630. public Collection<?> getListCellValue(Object obj)
  1631. {
  1632. Object value;
  1633. try
  1634. {
  1635. value = subMethod.invoke(obj, new Object[] {});
  1636. }
  1637. catch (Exception e)
  1638. {
  1639. return new ArrayList<Object>();
  1640. }
  1641. return (Collection<?>) value;
  1642. }
  1643. /**
  1644. * 获取对象的子列表方法
  1645. *
  1646. * @param name 名称
  1647. * @param pojoClass 类对象
  1648. * @return 子列表方法
  1649. */
  1650. public Method getSubMethod(String name, Class<?> pojoClass)
  1651. {
  1652. StringBuffer getMethodName = new StringBuffer("get");
  1653. getMethodName.append(name.substring(0, 1).toUpperCase());
  1654. getMethodName.append(name.substring(1));
  1655. Method method = null;
  1656. try
  1657. {
  1658. method = pojoClass.getMethod(getMethodName.toString(), new Class[] {});
  1659. }
  1660. catch (Exception e)
  1661. {
  1662. log.error("获取对象异常{}", e.getMessage());
  1663. }
  1664. return method;
  1665. }
  1666. }

以上导出数据到Excel可直接使用工具类导出

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/376163
推荐阅读
相关标签
  

闽ICP备14008679号