ExcelUtil.java 58 KB

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