ExcelUtil.java 49 KB

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