ExcelUtil.java 65 KB

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