ExcelUtil.java 45 KB

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