ExcelUtil.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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.math.BigDecimal;
  9. import java.text.SimpleDateFormat;
  10. import java.util.ArrayList;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.UUID;
  15. import org.apache.poi.hssf.usermodel.DVConstraint;
  16. import org.apache.poi.hssf.usermodel.HSSFCell;
  17. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  18. import org.apache.poi.hssf.usermodel.HSSFDataValidation;
  19. import org.apache.poi.hssf.usermodel.HSSFFont;
  20. import org.apache.poi.hssf.usermodel.HSSFRow;
  21. import org.apache.poi.hssf.usermodel.HSSFSheet;
  22. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  23. import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
  24. import org.apache.poi.ss.usermodel.Cell;
  25. import org.apache.poi.ss.usermodel.CellType;
  26. import org.apache.poi.ss.usermodel.FillPatternType;
  27. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  28. import org.apache.poi.ss.usermodel.Row;
  29. import org.apache.poi.ss.usermodel.Sheet;
  30. import org.apache.poi.ss.usermodel.VerticalAlignment;
  31. import org.apache.poi.ss.usermodel.Workbook;
  32. import org.apache.poi.ss.usermodel.WorkbookFactory;
  33. import org.apache.poi.ss.util.CellRangeAddressList;
  34. import org.slf4j.Logger;
  35. import org.slf4j.LoggerFactory;
  36. import com.ruoyi.common.utils.StringUtils;
  37. import com.ruoyi.framework.aspectj.lang.annotation.Excel;
  38. import com.ruoyi.framework.config.RuoYiConfig;
  39. import com.ruoyi.framework.web.domain.AjaxResult;
  40. /**
  41. * Excel相关处理
  42. *
  43. * @author ruoyi
  44. */
  45. public class ExcelUtil<T>
  46. {
  47. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  48. public Class<T> clazz;
  49. public ExcelUtil(Class<T> clazz)
  50. {
  51. this.clazz = clazz;
  52. }
  53. /**
  54. * 对excel表单默认第一个索引名转换成list
  55. *
  56. * @param input 输入流
  57. * @return 转换后集合
  58. */
  59. public List<T> importExcel(InputStream input) throws Exception
  60. {
  61. return importExcel(StringUtils.EMPTY, input);
  62. }
  63. /**
  64. * 对excel表单指定表格索引名转换成list
  65. *
  66. * @param sheetName 表格索引名
  67. * @param input 输入流
  68. * @return 转换后集合
  69. */
  70. public List<T> importExcel(String sheetName, InputStream input) throws Exception
  71. {
  72. List<T> list = new ArrayList<T>();
  73. Workbook workbook = WorkbookFactory.create(input);
  74. Sheet sheet = null;
  75. if (StringUtils.isNotEmpty(sheetName))
  76. {
  77. // 如果指定sheet名,则取指定sheet中的内容.
  78. sheet = workbook.getSheet(sheetName);
  79. }
  80. else
  81. {
  82. // 如果传入的sheet名不存在则默认指向第1个sheet.
  83. sheet = workbook.getSheetAt(0);
  84. }
  85. if (sheet == null)
  86. {
  87. throw new IOException("文件sheet不存在");
  88. }
  89. int rows = sheet.getPhysicalNumberOfRows();
  90. if (rows > 0)
  91. {
  92. // 默认序号
  93. int serialNum = 0;
  94. // 有数据时才处理 得到类的所有field.
  95. Field[] allFields = clazz.getDeclaredFields();
  96. // 定义一个map用于存放列的序号和field.
  97. Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
  98. for (int col = 0; col < allFields.length; col++)
  99. {
  100. Field field = allFields[col];
  101. // 将有注解的field存放到map中.
  102. if (field.isAnnotationPresent(Excel.class))
  103. {
  104. // 设置类的私有字段属性可访问.
  105. field.setAccessible(true);
  106. fieldsMap.put(++serialNum, field);
  107. }
  108. }
  109. for (int i = 1; i < rows; i++)
  110. {
  111. // 从第2行开始取数据,默认第一行是表头.
  112. Row row = sheet.getRow(i);
  113. int cellNum = serialNum;
  114. T entity = null;
  115. for (int j = 0; j < cellNum; j++)
  116. {
  117. Cell cell = row.getCell(j);
  118. if (cell == null)
  119. {
  120. continue;
  121. }
  122. else
  123. {
  124. // 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了
  125. row.getCell(j).setCellType(CellType.STRING);
  126. cell = row.getCell(j);
  127. }
  128. String c = cell.getStringCellValue();
  129. if (StringUtils.isEmpty(c))
  130. {
  131. continue;
  132. }
  133. // 如果不存在实例则新建.
  134. entity = (entity == null ? clazz.newInstance() : entity);
  135. // 从map中得到对应列的field.
  136. Field field = fieldsMap.get(j + 1);
  137. // 取得类型,并根据对象类型设置值.
  138. Class<?> fieldType = field.getType();
  139. if (String.class == fieldType)
  140. {
  141. field.set(entity, String.valueOf(c));
  142. }
  143. else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType))
  144. {
  145. field.set(entity, Integer.parseInt(c));
  146. }
  147. else if ((Long.TYPE == fieldType) || (Long.class == fieldType))
  148. {
  149. field.set(entity, Long.valueOf(c));
  150. }
  151. else if ((Float.TYPE == fieldType) || (Float.class == fieldType))
  152. {
  153. field.set(entity, Float.valueOf(c));
  154. }
  155. else if ((Short.TYPE == fieldType) || (Short.class == fieldType))
  156. {
  157. field.set(entity, Short.valueOf(c));
  158. }
  159. else if ((Double.TYPE == fieldType) || (Double.class == fieldType))
  160. {
  161. field.set(entity, Double.valueOf(c));
  162. }
  163. else if (Character.TYPE == fieldType)
  164. {
  165. if ((c != null) && (c.length() > 0))
  166. {
  167. field.set(entity, Character.valueOf(c.charAt(0)));
  168. }
  169. }
  170. else if (java.util.Date.class == fieldType)
  171. {
  172. if (cell.getCellTypeEnum() == CellType.NUMERIC)
  173. {
  174. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  175. cell.setCellValue(sdf.format(cell.getNumericCellValue()));
  176. c = sdf.format(cell.getNumericCellValue());
  177. }
  178. else
  179. {
  180. c = cell.getStringCellValue();
  181. }
  182. }
  183. else if (java.math.BigDecimal.class == fieldType)
  184. {
  185. c = cell.getStringCellValue();
  186. }
  187. }
  188. if (entity != null)
  189. {
  190. list.add(entity);
  191. }
  192. }
  193. }
  194. return list;
  195. }
  196. /**
  197. * 对list数据源将其里面的数据导入到excel表单
  198. *
  199. * @param list 导出数据集合
  200. * @param sheetName 工作表的名称
  201. * @return 结果
  202. */
  203. public AjaxResult exportExcel(List<T> list, String sheetName)
  204. {
  205. OutputStream out = null;
  206. HSSFWorkbook workbook = null;
  207. try
  208. {
  209. // 得到所有定义字段
  210. Field[] allFields = clazz.getDeclaredFields();
  211. List<Field> fields = new ArrayList<Field>();
  212. // 得到所有field并存放到一个list中.
  213. for (Field field : allFields)
  214. {
  215. if (field.isAnnotationPresent(Excel.class))
  216. {
  217. fields.add(field);
  218. }
  219. }
  220. // 产生工作薄对象
  221. workbook = new HSSFWorkbook();
  222. // excel2003中每个sheet中最多有65536行
  223. int sheetSize = 65536;
  224. // 取出一共有多少个sheet.
  225. double sheetNo = Math.ceil(list.size() / sheetSize);
  226. for (int index = 0; index <= sheetNo; index++)
  227. {
  228. // 产生工作表对象
  229. HSSFSheet sheet = workbook.createSheet();
  230. if (sheetNo == 0)
  231. {
  232. workbook.setSheetName(index, sheetName);
  233. }
  234. else
  235. {
  236. // 设置工作表的名称.
  237. workbook.setSheetName(index, sheetName + index);
  238. }
  239. HSSFRow row;
  240. HSSFCell cell; // 产生单元格
  241. // 产生一行
  242. row = sheet.createRow(0);
  243. // 写入各个字段的列头名称
  244. for (int i = 0; i < fields.size(); i++)
  245. {
  246. Field field = fields.get(i);
  247. Excel attr = field.getAnnotation(Excel.class);
  248. // 创建列
  249. cell = row.createCell(i);
  250. // 设置列中写入内容为String类型
  251. cell.setCellType(CellType.STRING);
  252. HSSFCellStyle cellStyle = workbook.createCellStyle();
  253. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  254. cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  255. if (attr.name().indexOf("注:") >= 0)
  256. {
  257. HSSFFont font = workbook.createFont();
  258. font.setColor(HSSFFont.COLOR_RED);
  259. cellStyle.setFont(font);
  260. cellStyle.setFillForegroundColor(HSSFColorPredefined.YELLOW.getIndex());
  261. sheet.setColumnWidth(i, 6000);
  262. }
  263. else
  264. {
  265. HSSFFont font = workbook.createFont();
  266. // 粗体显示
  267. font.setBold(true);
  268. // 选择需要用到的字体格式
  269. cellStyle.setFont(font);
  270. cellStyle.setFillForegroundColor(HSSFColorPredefined.LIGHT_YELLOW.getIndex());
  271. // 设置列宽
  272. sheet.setColumnWidth(i, 3766);
  273. }
  274. cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  275. cellStyle.setWrapText(true);
  276. cell.setCellStyle(cellStyle);
  277. // 写入列名
  278. cell.setCellValue(attr.name());
  279. // 如果设置了提示信息则鼠标放上去提示.
  280. if (StringUtils.isNotEmpty(attr.prompt()))
  281. {
  282. // 这里默认设了2-101列提示.
  283. setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, i, i);
  284. }
  285. // 如果设置了combo属性则本列只能选择不能输入
  286. if (attr.combo().length > 0)
  287. {
  288. // 这里默认设了2-101列只能选择不能输入.
  289. setHSSFValidation(sheet, attr.combo(), 1, 100, i, i);
  290. }
  291. }
  292. int startNo = index * sheetSize;
  293. int endNo = Math.min(startNo + sheetSize, list.size());
  294. // 写入各条记录,每条记录对应excel表中的一行
  295. HSSFCellStyle cs = workbook.createCellStyle();
  296. cs.setAlignment(HorizontalAlignment.CENTER);
  297. cs.setVerticalAlignment(VerticalAlignment.CENTER);
  298. for (int i = startNo; i < endNo; i++)
  299. {
  300. row = sheet.createRow(i + 1 - startNo);
  301. // 得到导出对象.
  302. T vo = (T) list.get(i);
  303. for (int j = 0; j < fields.size(); j++)
  304. {
  305. // 获得field.
  306. Field field = fields.get(j);
  307. // 设置实体类私有属性可访问
  308. field.setAccessible(true);
  309. Excel attr = field.getAnnotation(Excel.class);
  310. try
  311. {
  312. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  313. if (attr.isExport())
  314. {
  315. // 创建cell
  316. cell = row.createCell(j);
  317. cell.setCellStyle(cs);
  318. try
  319. {
  320. if (String.valueOf(field.get(vo)).length() > 10)
  321. {
  322. throw new Exception("长度超过10位就不用转数字了");
  323. }
  324. // 如果可以转成数字则导出为数字类型
  325. BigDecimal bc = new BigDecimal(String.valueOf(field.get(vo)));
  326. cell.setCellType(CellType.NUMERIC);
  327. cell.setCellValue(bc.doubleValue());
  328. }
  329. catch (Exception e)
  330. {
  331. cell.setCellType(CellType.STRING);
  332. if (vo == null)
  333. {
  334. // 如果数据存在就填入,不存在填入空格.
  335. cell.setCellValue("");
  336. }
  337. else
  338. {
  339. // 如果数据存在就填入,不存在填入空格.
  340. cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo)));
  341. }
  342. }
  343. }
  344. }
  345. catch (Exception e)
  346. {
  347. log.error("导出Excel失败{}", e.getMessage());
  348. }
  349. }
  350. }
  351. }
  352. String filename = encodingFilename(sheetName);
  353. out = new FileOutputStream(getAbsoluteFile(filename));
  354. workbook.write(out);
  355. return AjaxResult.success(filename);
  356. }
  357. catch (Exception e)
  358. {
  359. log.error("导出Excel异常{}", e.getMessage());
  360. return AjaxResult.error("导出Excel失败,请联系网站管理员!");
  361. }
  362. finally
  363. {
  364. if (workbook != null)
  365. {
  366. try
  367. {
  368. workbook.close();
  369. }
  370. catch (IOException e1)
  371. {
  372. e1.printStackTrace();
  373. }
  374. }
  375. if (out != null)
  376. {
  377. try
  378. {
  379. out.close();
  380. }
  381. catch (IOException e1)
  382. {
  383. e1.printStackTrace();
  384. }
  385. }
  386. }
  387. }
  388. /**
  389. * 设置单元格上提示
  390. *
  391. * @param sheet 要设置的sheet.
  392. * @param promptTitle 标题
  393. * @param promptContent 内容
  394. * @param firstRow 开始行
  395. * @param endRow 结束行
  396. * @param firstCol 开始列
  397. * @param endCol 结束列
  398. * @return 设置好的sheet.
  399. */
  400. public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow,
  401. int endRow, int firstCol, int endCol)
  402. {
  403. // 构造constraint对象
  404. DVConstraint constraint = DVConstraint.createCustomFormulaConstraint("DD1");
  405. // 四个参数分别是:起始行、终止行、起始列、终止列
  406. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  407. // 数据有效性对象
  408. HSSFDataValidation dataValidationView = new HSSFDataValidation(regions, constraint);
  409. dataValidationView.createPromptBox(promptTitle, promptContent);
  410. sheet.addValidationData(dataValidationView);
  411. return sheet;
  412. }
  413. /**
  414. * 设置某些列的值只能输入预制的数据,显示下拉框.
  415. *
  416. * @param sheet 要设置的sheet.
  417. * @param textlist 下拉框显示的内容
  418. * @param firstRow 开始行
  419. * @param endRow 结束行
  420. * @param firstCol 开始列
  421. * @param endCol 结束列
  422. * @return 设置好的sheet.
  423. */
  424. public static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow,
  425. int firstCol, int endCol)
  426. {
  427. // 加载下拉列表内容
  428. DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist);
  429. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  430. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  431. // 数据有效性对象
  432. HSSFDataValidation dataValidationList = new HSSFDataValidation(regions, constraint);
  433. sheet.addValidationData(dataValidationList);
  434. return sheet;
  435. }
  436. /**
  437. * 编码文件名
  438. */
  439. public String encodingFilename(String filename)
  440. {
  441. filename = UUID.randomUUID().toString() + "_" + filename + ".xls";
  442. return filename;
  443. }
  444. /**
  445. * 获取下载路径
  446. *
  447. * @param filename 文件名称
  448. */
  449. public String getAbsoluteFile(String filename)
  450. {
  451. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  452. File desc = new File(downloadPath);
  453. if (!desc.getParentFile().exists())
  454. {
  455. desc.getParentFile().mkdirs();
  456. }
  457. return downloadPath;
  458. }
  459. }