ExcelUtil.java 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  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.cloneStyleFrom(styles.get("data"));
  612. style.setAlignment(HorizontalAlignment.CENTER);
  613. style.setVerticalAlignment(VerticalAlignment.CENTER);
  614. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  615. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  616. Font headerFont = wb.createFont();
  617. headerFont.setFontName("Arial");
  618. headerFont.setFontHeightInPoints((short) 10);
  619. headerFont.setBold(true);
  620. headerFont.setColor(IndexedColors.WHITE.getIndex());
  621. style.setFont(headerFont);
  622. styles.put("header", style);
  623. style = wb.createCellStyle();
  624. style.setAlignment(HorizontalAlignment.CENTER);
  625. style.setVerticalAlignment(VerticalAlignment.CENTER);
  626. Font totalFont = wb.createFont();
  627. totalFont.setFontName("Arial");
  628. totalFont.setFontHeightInPoints((short) 10);
  629. style.setFont(totalFont);
  630. styles.put("total", style);
  631. return styles;
  632. }
  633. /**
  634. * 创建单元格
  635. */
  636. public Cell createCell(Excel attr, Row row, int column)
  637. {
  638. // 创建列
  639. Cell cell = row.createCell(column);
  640. // 写入列信息
  641. cell.setCellValue(attr.name());
  642. setDataValidation(attr, row, column);
  643. cell.setCellStyle(styles.get("header"));
  644. return cell;
  645. }
  646. /**
  647. * 设置单元格信息
  648. *
  649. * @param value 单元格值
  650. * @param attr 注解相关
  651. * @param cell 单元格信息
  652. */
  653. public void setCellVo(Object value, Excel attr, Cell cell)
  654. {
  655. if (ColumnType.STRING == attr.cellType())
  656. {
  657. String cellValue = Convert.toStr(value);
  658. // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。
  659. if (StringUtils.startsWithAny(cellValue, FORMULA_STR))
  660. {
  661. cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
  662. }
  663. cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix());
  664. }
  665. else if (ColumnType.NUMERIC == attr.cellType())
  666. {
  667. if (StringUtils.isNotNull(value))
  668. {
  669. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  670. }
  671. }
  672. else if (ColumnType.IMAGE == attr.cellType())
  673. {
  674. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  675. String imagePath = Convert.toStr(value);
  676. if (StringUtils.isNotEmpty(imagePath))
  677. {
  678. byte[] data = ImageUtils.getImage(imagePath);
  679. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  680. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  681. }
  682. }
  683. }
  684. /**
  685. * 获取画布
  686. */
  687. public static Drawing<?> getDrawingPatriarch(Sheet sheet)
  688. {
  689. if (sheet.getDrawingPatriarch() == null)
  690. {
  691. sheet.createDrawingPatriarch();
  692. }
  693. return sheet.getDrawingPatriarch();
  694. }
  695. /**
  696. * 获取图片类型,设置图片插入类型
  697. */
  698. public int getImageType(byte[] value)
  699. {
  700. String type = FileTypeUtils.getFileExtendName(value);
  701. if ("JPG".equalsIgnoreCase(type))
  702. {
  703. return Workbook.PICTURE_TYPE_JPEG;
  704. }
  705. else if ("PNG".equalsIgnoreCase(type))
  706. {
  707. return Workbook.PICTURE_TYPE_PNG;
  708. }
  709. return Workbook.PICTURE_TYPE_JPEG;
  710. }
  711. /**
  712. * 创建表格样式
  713. */
  714. public void setDataValidation(Excel attr, Row row, int column)
  715. {
  716. if (attr.name().indexOf("注:") >= 0)
  717. {
  718. sheet.setColumnWidth(column, 6000);
  719. }
  720. else
  721. {
  722. // 设置列宽
  723. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  724. }
  725. if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0)
  726. {
  727. // 提示信息或只能选择不能输入的列内容.
  728. setPromptOrValidation(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  729. }
  730. }
  731. /**
  732. * 添加单元格
  733. */
  734. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  735. {
  736. Cell cell = null;
  737. try
  738. {
  739. // 设置行高
  740. row.setHeight(maxHeight);
  741. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  742. if (attr.isExport())
  743. {
  744. // 创建cell
  745. cell = row.createCell(column);
  746. setDataCell(cell, attr);
  747. // 用于读取对象中的属性
  748. Object value = getTargetValue(vo, field, attr);
  749. String dateFormat = attr.dateFormat();
  750. String readConverterExp = attr.readConverterExp();
  751. String separator = attr.separator();
  752. String dictType = attr.dictType();
  753. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  754. {
  755. cell.setCellValue(parseDateToStr(dateFormat, value));
  756. }
  757. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  758. {
  759. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  760. }
  761. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  762. {
  763. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  764. }
  765. else if (value instanceof BigDecimal && -1 != attr.scale())
  766. {
  767. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
  768. }
  769. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  770. {
  771. cell.setCellValue(dataFormatHandlerAdapter(value, attr));
  772. }
  773. else
  774. {
  775. // 设置列类型
  776. setCellVo(value, attr, cell);
  777. }
  778. addStatisticsData(column, Convert.toStr(value), attr);
  779. }
  780. }
  781. catch (Exception e)
  782. {
  783. log.error("导出Excel失败{}", e);
  784. }
  785. return cell;
  786. }
  787. /**
  788. * 设置单元格样式
  789. *
  790. * @param cell 单元格
  791. * @param excel 注解信息
  792. */
  793. public void setDataCell(Cell cell, Excel excel)
  794. {
  795. CellStyle style = wb.createCellStyle();
  796. style.setAlignment(HorizontalAlignment.CENTER);
  797. style.setVerticalAlignment(VerticalAlignment.CENTER);
  798. style.setBorderRight(BorderStyle.THIN);
  799. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  800. style.setBorderLeft(BorderStyle.THIN);
  801. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  802. style.setBorderTop(BorderStyle.THIN);
  803. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  804. style.setBorderBottom(BorderStyle.THIN);
  805. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  806. style.setAlignment(excel.align());
  807. Font dataFont = wb.createFont();
  808. dataFont.setFontName("Arial");
  809. dataFont.setFontHeightInPoints((short) 10);
  810. dataFont.setColor(excel.color().index);
  811. style.setFont(dataFont);
  812. cell.setCellStyle(style);
  813. }
  814. /**
  815. * 设置 POI XSSFSheet 单元格提示或选择框
  816. *
  817. * @param sheet 表单
  818. * @param textlist 下拉框显示的内容
  819. * @param promptContent 提示内容
  820. * @param firstRow 开始行
  821. * @param endRow 结束行
  822. * @param firstCol 开始列
  823. * @param endCol 结束列
  824. */
  825. public void setPromptOrValidation(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow,
  826. int firstCol, int endCol)
  827. {
  828. DataValidationHelper helper = sheet.getDataValidationHelper();
  829. DataValidationConstraint constraint = textlist.length > 0 ? helper.createExplicitListConstraint(textlist) : helper.createCustomConstraint("DD1");
  830. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  831. DataValidation dataValidation = helper.createValidation(constraint, regions);
  832. if (StringUtils.isNotEmpty(promptContent))
  833. {
  834. // 如果设置了提示信息则鼠标放上去提示
  835. dataValidation.createPromptBox("", promptContent);
  836. dataValidation.setShowPromptBox(true);
  837. }
  838. // 处理Excel兼容性问题
  839. if (dataValidation instanceof XSSFDataValidation)
  840. {
  841. dataValidation.setSuppressDropDownArrow(true);
  842. dataValidation.setShowErrorBox(true);
  843. }
  844. else
  845. {
  846. dataValidation.setSuppressDropDownArrow(false);
  847. }
  848. sheet.addValidationData(dataValidation);
  849. }
  850. /**
  851. * 解析导出值 0=男,1=女,2=未知
  852. *
  853. * @param propertyValue 参数值
  854. * @param converterExp 翻译注解
  855. * @param separator 分隔符
  856. * @return 解析后值
  857. */
  858. public static String convertByExp(String propertyValue, String converterExp, String separator)
  859. {
  860. StringBuilder propertyString = new StringBuilder();
  861. String[] convertSource = converterExp.split(",");
  862. for (String item : convertSource)
  863. {
  864. String[] itemArray = item.split("=");
  865. if (StringUtils.containsAny(separator, propertyValue))
  866. {
  867. for (String value : propertyValue.split(separator))
  868. {
  869. if (itemArray[0].equals(value))
  870. {
  871. propertyString.append(itemArray[1] + separator);
  872. break;
  873. }
  874. }
  875. }
  876. else
  877. {
  878. if (itemArray[0].equals(propertyValue))
  879. {
  880. return itemArray[1];
  881. }
  882. }
  883. }
  884. return StringUtils.stripEnd(propertyString.toString(), separator);
  885. }
  886. /**
  887. * 反向解析值 男=0,女=1,未知=2
  888. *
  889. * @param propertyValue 参数值
  890. * @param converterExp 翻译注解
  891. * @param separator 分隔符
  892. * @return 解析后值
  893. */
  894. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  895. {
  896. StringBuilder propertyString = new StringBuilder();
  897. String[] convertSource = converterExp.split(",");
  898. for (String item : convertSource)
  899. {
  900. String[] itemArray = item.split("=");
  901. if (StringUtils.containsAny(separator, propertyValue))
  902. {
  903. for (String value : propertyValue.split(separator))
  904. {
  905. if (itemArray[1].equals(value))
  906. {
  907. propertyString.append(itemArray[0] + separator);
  908. break;
  909. }
  910. }
  911. }
  912. else
  913. {
  914. if (itemArray[1].equals(propertyValue))
  915. {
  916. return itemArray[0];
  917. }
  918. }
  919. }
  920. return StringUtils.stripEnd(propertyString.toString(), separator);
  921. }
  922. /**
  923. * 解析字典值
  924. *
  925. * @param dictValue 字典值
  926. * @param dictType 字典类型
  927. * @param separator 分隔符
  928. * @return 字典标签
  929. */
  930. public static String convertDictByExp(String dictValue, String dictType, String separator)
  931. {
  932. return DictUtils.getDictLabel(dictType, dictValue, separator);
  933. }
  934. /**
  935. * 反向解析值字典值
  936. *
  937. * @param dictLabel 字典标签
  938. * @param dictType 字典类型
  939. * @param separator 分隔符
  940. * @return 字典值
  941. */
  942. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  943. {
  944. return DictUtils.getDictValue(dictType, dictLabel, separator);
  945. }
  946. /**
  947. * 数据处理器
  948. *
  949. * @param value 数据值
  950. * @param excel 数据注解
  951. * @return
  952. */
  953. public String dataFormatHandlerAdapter(Object value, Excel excel)
  954. {
  955. try
  956. {
  957. Object instance = excel.handler().newInstance();
  958. Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class });
  959. value = formatMethod.invoke(instance, value, excel.args());
  960. }
  961. catch (Exception e)
  962. {
  963. log.error("不能格式化数据 " + excel.handler(), e.getMessage());
  964. }
  965. return Convert.toStr(value);
  966. }
  967. /**
  968. * 合计统计信息
  969. */
  970. private void addStatisticsData(Integer index, String text, Excel entity)
  971. {
  972. if (entity != null && entity.isStatistics())
  973. {
  974. Double temp = 0D;
  975. if (!statistics.containsKey(index))
  976. {
  977. statistics.put(index, temp);
  978. }
  979. try
  980. {
  981. temp = Double.valueOf(text);
  982. }
  983. catch (NumberFormatException e)
  984. {
  985. }
  986. statistics.put(index, statistics.get(index) + temp);
  987. }
  988. }
  989. /**
  990. * 创建统计行
  991. */
  992. public void addStatisticsRow()
  993. {
  994. if (statistics.size() > 0)
  995. {
  996. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  997. Set<Integer> keys = statistics.keySet();
  998. Cell cell = row.createCell(0);
  999. cell.setCellStyle(styles.get("total"));
  1000. cell.setCellValue("合计");
  1001. for (Integer key : keys)
  1002. {
  1003. cell = row.createCell(key);
  1004. cell.setCellStyle(styles.get("total"));
  1005. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  1006. }
  1007. statistics.clear();
  1008. }
  1009. }
  1010. /**
  1011. * 编码文件名
  1012. */
  1013. public String encodingFilename(String filename)
  1014. {
  1015. filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  1016. return filename;
  1017. }
  1018. /**
  1019. * 获取下载路径
  1020. *
  1021. * @param filename 文件名称
  1022. */
  1023. public String getAbsoluteFile(String filename)
  1024. {
  1025. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  1026. File desc = new File(downloadPath);
  1027. if (!desc.getParentFile().exists())
  1028. {
  1029. desc.getParentFile().mkdirs();
  1030. }
  1031. return downloadPath;
  1032. }
  1033. /**
  1034. * 获取bean中的属性值
  1035. *
  1036. * @param vo 实体对象
  1037. * @param field 字段
  1038. * @param excel 注解
  1039. * @return 最终的属性值
  1040. * @throws Exception
  1041. */
  1042. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  1043. {
  1044. Object o = field.get(vo);
  1045. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1046. {
  1047. String target = excel.targetAttr();
  1048. if (target.contains("."))
  1049. {
  1050. String[] targets = target.split("[.]");
  1051. for (String name : targets)
  1052. {
  1053. o = getValue(o, name);
  1054. }
  1055. }
  1056. else
  1057. {
  1058. o = getValue(o, target);
  1059. }
  1060. }
  1061. return o;
  1062. }
  1063. /**
  1064. * 以类的属性的get方法方法形式获取值
  1065. *
  1066. * @param o
  1067. * @param name
  1068. * @return value
  1069. * @throws Exception
  1070. */
  1071. private Object getValue(Object o, String name) throws Exception
  1072. {
  1073. if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
  1074. {
  1075. Class<?> clazz = o.getClass();
  1076. Field field = clazz.getDeclaredField(name);
  1077. field.setAccessible(true);
  1078. o = field.get(o);
  1079. }
  1080. return o;
  1081. }
  1082. /**
  1083. * 得到所有定义字段
  1084. */
  1085. private void createExcelField()
  1086. {
  1087. this.fields = getFields();
  1088. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  1089. this.maxHeight = getRowHeight();
  1090. }
  1091. /**
  1092. * 获取字段注解信息
  1093. */
  1094. public List<Object[]> getFields()
  1095. {
  1096. List<Object[]> fields = new ArrayList<Object[]>();
  1097. List<Field> tempFields = new ArrayList<>();
  1098. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1099. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1100. for (Field field : tempFields)
  1101. {
  1102. // 单注解
  1103. if (field.isAnnotationPresent(Excel.class))
  1104. {
  1105. Excel attr = field.getAnnotation(Excel.class);
  1106. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1107. {
  1108. field.setAccessible(true);
  1109. fields.add(new Object[] { field, attr });
  1110. }
  1111. }
  1112. // 多注解
  1113. if (field.isAnnotationPresent(Excels.class))
  1114. {
  1115. Excels attrs = field.getAnnotation(Excels.class);
  1116. Excel[] excels = attrs.value();
  1117. for (Excel attr : excels)
  1118. {
  1119. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1120. {
  1121. field.setAccessible(true);
  1122. fields.add(new Object[] { field, attr });
  1123. }
  1124. }
  1125. }
  1126. }
  1127. return fields;
  1128. }
  1129. /**
  1130. * 根据注解获取最大行高
  1131. */
  1132. public short getRowHeight()
  1133. {
  1134. double maxHeight = 0;
  1135. for (Object[] os : this.fields)
  1136. {
  1137. Excel excel = (Excel) os[1];
  1138. maxHeight = Math.max(maxHeight, excel.height());
  1139. }
  1140. return (short) (maxHeight * 20);
  1141. }
  1142. /**
  1143. * 创建一个工作簿
  1144. */
  1145. public void createWorkbook()
  1146. {
  1147. this.wb = new SXSSFWorkbook(500);
  1148. this.sheet = wb.createSheet();
  1149. wb.setSheetName(0, sheetName);
  1150. this.styles = createStyles(wb);
  1151. }
  1152. /**
  1153. * 创建工作表
  1154. *
  1155. * @param sheetNo sheet数量
  1156. * @param index 序号
  1157. */
  1158. public void createSheet(int sheetNo, int index)
  1159. {
  1160. // 设置工作表的名称.
  1161. if (sheetNo > 1 && index > 0)
  1162. {
  1163. this.sheet = wb.createSheet();
  1164. this.createTitle();
  1165. wb.setSheetName(index, sheetName + index);
  1166. }
  1167. }
  1168. /**
  1169. * 获取单元格值
  1170. *
  1171. * @param row 获取的行
  1172. * @param column 获取单元格列号
  1173. * @return 单元格值
  1174. */
  1175. public Object getCellValue(Row row, int column)
  1176. {
  1177. if (row == null)
  1178. {
  1179. return row;
  1180. }
  1181. Object val = "";
  1182. try
  1183. {
  1184. Cell cell = row.getCell(column);
  1185. if (StringUtils.isNotNull(cell))
  1186. {
  1187. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1188. {
  1189. val = cell.getNumericCellValue();
  1190. if (DateUtil.isCellDateFormatted(cell))
  1191. {
  1192. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1193. }
  1194. else
  1195. {
  1196. if ((Double) val % 1 != 0)
  1197. {
  1198. val = new BigDecimal(val.toString());
  1199. }
  1200. else
  1201. {
  1202. val = new DecimalFormat("0").format(val);
  1203. }
  1204. }
  1205. }
  1206. else if (cell.getCellType() == CellType.STRING)
  1207. {
  1208. val = cell.getStringCellValue();
  1209. }
  1210. else if (cell.getCellType() == CellType.BOOLEAN)
  1211. {
  1212. val = cell.getBooleanCellValue();
  1213. }
  1214. else if (cell.getCellType() == CellType.ERROR)
  1215. {
  1216. val = cell.getErrorCellValue();
  1217. }
  1218. }
  1219. }
  1220. catch (Exception e)
  1221. {
  1222. return val;
  1223. }
  1224. return val;
  1225. }
  1226. /**
  1227. * 判断是否是空行
  1228. *
  1229. * @param row 判断的行
  1230. * @return
  1231. */
  1232. private boolean isRowEmpty(Row row)
  1233. {
  1234. if (row == null)
  1235. {
  1236. return true;
  1237. }
  1238. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
  1239. {
  1240. Cell cell = row.getCell(i);
  1241. if (cell != null && cell.getCellType() != CellType.BLANK)
  1242. {
  1243. return false;
  1244. }
  1245. }
  1246. return true;
  1247. }
  1248. /**
  1249. * 获取Excel2003图片
  1250. *
  1251. * @param sheet 当前sheet对象
  1252. * @param workbook 工作簿对象
  1253. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1254. */
  1255. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
  1256. {
  1257. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1258. List<HSSFPictureData> pictures = workbook.getAllPictures();
  1259. if (!pictures.isEmpty())
  1260. {
  1261. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
  1262. {
  1263. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
  1264. if (shape instanceof HSSFPicture)
  1265. {
  1266. HSSFPicture pic = (HSSFPicture) shape;
  1267. int pictureIndex = pic.getPictureIndex() - 1;
  1268. HSSFPictureData picData = pictures.get(pictureIndex);
  1269. String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
  1270. sheetIndexPicMap.put(picIndex, picData);
  1271. }
  1272. }
  1273. return sheetIndexPicMap;
  1274. }
  1275. else
  1276. {
  1277. return sheetIndexPicMap;
  1278. }
  1279. }
  1280. /**
  1281. * 获取Excel2007图片
  1282. *
  1283. * @param sheet 当前sheet对象
  1284. * @param workbook 工作簿对象
  1285. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1286. */
  1287. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
  1288. {
  1289. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1290. for (POIXMLDocumentPart dr : sheet.getRelations())
  1291. {
  1292. if (dr instanceof XSSFDrawing)
  1293. {
  1294. XSSFDrawing drawing = (XSSFDrawing) dr;
  1295. List<XSSFShape> shapes = drawing.getShapes();
  1296. for (XSSFShape shape : shapes)
  1297. {
  1298. if (shape instanceof XSSFPicture)
  1299. {
  1300. XSSFPicture pic = (XSSFPicture) shape;
  1301. XSSFClientAnchor anchor = pic.getPreferredSize();
  1302. CTMarker ctMarker = anchor.getFrom();
  1303. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
  1304. sheetIndexPicMap.put(picIndex, pic.getPictureData());
  1305. }
  1306. }
  1307. }
  1308. }
  1309. return sheetIndexPicMap;
  1310. }
  1311. /**
  1312. * 格式化不同类型的日期对象
  1313. *
  1314. * @param dateFormat 日期格式
  1315. * @param val 被格式化的日期对象
  1316. * @return 格式化后的日期字符
  1317. */
  1318. public String parseDateToStr(String dateFormat, Object val)
  1319. {
  1320. if (val == null)
  1321. {
  1322. return "";
  1323. }
  1324. String str;
  1325. if (val instanceof Date)
  1326. {
  1327. str = DateUtils.parseDateToStr(dateFormat, (Date) val);
  1328. }
  1329. else if (val instanceof LocalDateTime)
  1330. {
  1331. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDateTime) val));
  1332. }
  1333. else if (val instanceof LocalDate)
  1334. {
  1335. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val));
  1336. }
  1337. else
  1338. {
  1339. str = val.toString();
  1340. }
  1341. return str;
  1342. }
  1343. }