ExcelUtil.java 49 KB

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