ExcelUtil.java 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. package com.rf.youth.utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.rf.youth.file.excel.ExcelBean;
  4. import jodd.util.StringUtil;
  5. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  6. import org.apache.poi.ss.usermodel.*;
  7. import org.apache.poi.ss.util.CellRangeAddress;
  8. import org.apache.poi.xssf.usermodel.*;
  9. import java.beans.PropertyDescriptor;
  10. import java.io.File;
  11. import java.io.FileOutputStream;
  12. import java.io.InputStream;
  13. import java.lang.reflect.Method;
  14. import java.math.BigDecimal;
  15. import java.text.DecimalFormat;
  16. import java.text.NumberFormat;
  17. import java.text.SimpleDateFormat;
  18. import java.util.ArrayList;
  19. import java.util.Date;
  20. import java.util.List;
  21. import java.util.Map;
  22. /**
  23. * @author zzf
  24. * @description:Excel 导出工具了哦
  25. * @date 2021/1/27 9:18
  26. */
  27. public class ExcelUtil {
  28. /**
  29. * excel 版本
  30. **/
  31. private final static String excel2003L = ".xls";
  32. private final static String excel2007U = ".xlsx";
  33. /**
  34. * Excel导入
  35. */
  36. public static List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception {
  37. List<List<Object>> list = null;
  38. //创建Excel工作薄
  39. Workbook work = getWorkbook(in, fileName);
  40. if (null == work) {
  41. throw new Exception("创建Excel工作薄为空!");
  42. }
  43. Sheet sheet = null;
  44. Row row = null;
  45. Cell cell = null;
  46. list = new ArrayList<List<Object>>();
  47. //遍历Excel中所有的sheet
  48. System.out.println("work.getNumberOfSheets():" + work.getNumberOfSheets());
  49. for (int i = 0; i < work.getNumberOfSheets() - 1; i++) {
  50. sheet = work.getSheetAt(i);
  51. if (sheet == null) {
  52. continue;
  53. }
  54. int sheetSize = 0;
  55. //遍历当前sheet中的所有行
  56. //包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部
  57. for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
  58. //读取一行
  59. row = sheet.getRow(j);
  60. //去掉空行和表头
  61. if (row.getFirstCellNum() == j) {
  62. sheetSize = row.getLastCellNum();
  63. }
  64. if (row == null || row.getFirstCellNum() == j) {
  65. continue;
  66. }
  67. //遍历所有的列
  68. List<Object> li = new ArrayList<Object>();
  69. for (int y = row.getFirstCellNum(); y < sheetSize; y++) {
  70. cell = row.getCell(y);
  71. li.add(cell != null ? getCellValue(cell) : null);
  72. }
  73. list.add(li);
  74. }
  75. }
  76. return list;
  77. }
  78. /**
  79. * Excel分sheet导入
  80. */
  81. public static List<List<List<Object>>> getBankListByExcelSheet(InputStream in, String fileName) throws Exception {
  82. List<List<List<Object>>> list = null;
  83. //创建Excel工作薄
  84. Workbook work = getWorkbook(in, fileName);
  85. if (null == work) {
  86. throw new Exception("创建Excel工作薄为空!");
  87. }
  88. Sheet sheet = null;
  89. Row row = null;
  90. Cell cell = null;
  91. list = new ArrayList<List<List<Object>>>();
  92. //遍历Excel中所有的sheet
  93. for (int i = 0; i < work.getNumberOfSheets() - 1; i++) {
  94. List<List<Object>> sheets = new ArrayList<List<Object>>();
  95. sheet = work.getSheetAt(i);
  96. if (sheet == null) {
  97. continue;
  98. }
  99. int sheetSize = 0;
  100. //遍历当前sheet中的所有行
  101. //包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部
  102. for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
  103. //读取一行
  104. row = sheet.getRow(j);
  105. //去掉空行和表头
  106. if (row == null || row.getFirstCellNum() == j) {
  107. continue;
  108. }
  109. if (isAllRowEmpty(row, sheet.getRow(0))) {
  110. continue;
  111. }
  112. sheetSize = row.getLastCellNum();
  113. //遍历所有的列
  114. List<Object> li = new ArrayList<Object>();
  115. for (int y = row.getFirstCellNum(); y < sheetSize; y++) {
  116. cell = row.getCell(y);
  117. if (cell == null) {
  118. continue;
  119. }
  120. li.add(cell != null ? getCellValue(cell) : null);
  121. }
  122. sheets.add(li);
  123. }
  124. list.add(sheets);
  125. }
  126. return list;
  127. }
  128. /**
  129. * 验证excel是否全部为空
  130. *
  131. * @param row 当前行
  132. * @param firstRow 第一行标题行
  133. * @return
  134. */
  135. public static boolean isAllRowEmpty(Row row, Row firstRow) {
  136. int count = 0;
  137. //单元格数量
  138. int rowCount = firstRow.getLastCellNum() - firstRow.getFirstCellNum();
  139. //判断多少个单元格为空
  140. for (int c = 0; c < rowCount; c++) {
  141. Cell cell = row.getCell(c);
  142. if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK || StringUtil.isEmpty((cell + "").trim())) {
  143. count += 1;
  144. }
  145. }
  146. if (count == rowCount) {
  147. return true;
  148. }
  149. return false;
  150. }
  151. /**
  152. * 描述:根据文件后缀,自适应上传文件的版本
  153. */
  154. private static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
  155. Workbook wb = null;
  156. String fileType = fileName.substring(fileName.lastIndexOf("."));
  157. if (excel2003L.equals(fileType)) {
  158. //2003-
  159. wb = new HSSFWorkbook(inStr);
  160. } else if (excel2007U.equals(fileType)) {
  161. //2007+
  162. wb = new XSSFWorkbook(inStr);
  163. } else {
  164. throw new Exception("解析的文件格式有误!");
  165. }
  166. return wb;
  167. }
  168. /**
  169. * 描述:对表格中数值进行格式化
  170. */
  171. private static Object getCellValue(Cell cell) {
  172. Object value = null;
  173. //格式化字符类型的数字
  174. DecimalFormat df = new DecimalFormat("0");
  175. //日期格式化
  176. SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
  177. //格式化数字
  178. DecimalFormat df2 = new DecimalFormat("0.00");
  179. switch (cell.getCellType()) {
  180. case Cell.CELL_TYPE_STRING:
  181. value = cell.getRichStringCellValue().getString();
  182. break;
  183. case Cell.CELL_TYPE_NUMERIC:
  184. if ("General".equals(cell.getCellStyle().getDataFormatString())) {
  185. value = df.format(cell.getNumericCellValue());
  186. } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
  187. value = sdf.format(cell.getDateCellValue());
  188. } else {
  189. value = df2.format(cell.getNumericCellValue());
  190. }
  191. break;
  192. case Cell.CELL_TYPE_BOOLEAN:
  193. value = cell.getBooleanCellValue();
  194. break;
  195. case Cell.CELL_TYPE_BLANK:
  196. value = "";
  197. break;
  198. case Cell.CELL_TYPE_FORMULA: //公式类型
  199. try {
  200. if ("General".equals(cell.getCellStyle().getDataFormatString())) {
  201. value = df.format(cell.getNumericCellValue());
  202. } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
  203. value = sdf.format(cell.getDateCellValue());
  204. } else {
  205. value = df2.format(cell.getNumericCellValue());
  206. }
  207. } catch (IllegalStateException e) {
  208. value = String.valueOf(cell.getRichStringCellValue());
  209. }
  210. break;
  211. default:
  212. break;
  213. }
  214. return value;
  215. }
  216. /**
  217. * @param clazz 数据类
  218. * @param objs 导出数据列表
  219. * @param resultMap 计算结果,各项得分
  220. * @param map 表头
  221. * @param fileName 文件名
  222. * @param sheetName sheet页命
  223. * @return
  224. * @throws Exception
  225. */
  226. public static XSSFWorkbook createExcelFile(Class clazz, List objs, List<Map<String, String>> resultMap, Map<Integer, List<ExcelBean>> map, String fileName, String sheetName) throws Exception {
  227. // 创建新的Excel工作簿
  228. XSSFWorkbook workbook = new XSSFWorkbook();
  229. // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
  230. XSSFSheet sheet = workbook.createSheet(sheetName);
  231. // 以下为excel的字体样式以及excel的标题与内容的创建,下面会具体分析;
  232. //字体样式
  233. createFont(workbook);
  234. //创建标题(头)
  235. createTableHeader(sheet, map);
  236. //创建内容
  237. createTableRows(sheet, map, objs, resultMap, clazz);
  238. String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  239. // File file = new File("./"+date+"/"+sheetName+"/"+fileName);
  240. // if(!file.exists()){
  241. //// file.createNewFile();
  242. // file.mkdirs();
  243. // }
  244. FileOutputStream fileOutputStream = null;
  245. if (OSUtil.isLinux()) {
  246. File file = new File("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName);
  247. if (!file.exists()) {
  248. //file.createNewFile();
  249. file.mkdirs();
  250. }
  251. fileOutputStream = new FileOutputStream("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName + "/" + fileName);
  252. } else {
  253. File file = new File("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName);
  254. if (!file.exists()) {
  255. //file.createNewFile();
  256. file.mkdirs();
  257. }
  258. fileOutputStream = new FileOutputStream("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName + "/" + fileName);
  259. }
  260. // FileOutputStream fileOutputStream= new FileOutputStream("./"+date+"/"+sheetName+"/"+fileName);
  261. // FileOutputStream fileOutputStream= new FileOutputStream(file);
  262. workbook.write(fileOutputStream);
  263. fileOutputStream.close();
  264. return workbook;
  265. }
  266. /**
  267. * @param clazzs 数据类列表
  268. * @param objs 三个情绪识别题目列表
  269. * @param resultJson 三个情绪识别的答案
  270. * @param tableHeader 三个情绪识别的表头
  271. * @param fileName 文件名
  272. * @param sheetName sheet页
  273. * @return
  274. * @throws Exception
  275. */
  276. public static void createEALLExcelFile(List<Class> clazzs, Map<String, List> objs, JSONObject resultJson, List<Map<Integer, List<ExcelBean>>> tableHeader, String fileName, String sheetName) throws Exception {
  277. // 创建新的Excel工作簿
  278. XSSFWorkbook workbook = new XSSFWorkbook();
  279. // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
  280. XSSFSheet sheet = workbook.createSheet(sheetName);
  281. // 以下为excel的字体样式以及excel的标题与内容的创建,下面会具体分析;
  282. //字体样式
  283. createFont(workbook);
  284. //创建内容
  285. createEALLTableRows(sheet, objs, tableHeader, resultJson, clazzs);
  286. FileOutputStream fileOutputStream = null;
  287. if (OSUtil.isLinux()) {
  288. File file = new File("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName);
  289. if (!file.exists()) {
  290. file.mkdirs();
  291. }
  292. fileOutputStream = new FileOutputStream("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName + "/" + fileName);
  293. } else {
  294. File file = new File("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName);
  295. if (!file.exists()) {
  296. file.mkdirs();
  297. }
  298. fileOutputStream = new FileOutputStream("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName + "/" + fileName);
  299. }
  300. workbook.write(fileOutputStream);
  301. fileOutputStream.close();
  302. //return workbook;
  303. }
  304. private static void createEALLTableRows(XSSFSheet sheet, Map<String, List> objsMap, List<Map<Integer, List<ExcelBean>>> tableHeader, JSONObject resultJson, List<Class> clazzs) throws Exception {
  305. int rowindex = 0;
  306. for (int j = 0; j < tableHeader.size(); j++) {
  307. Map<Integer, List<ExcelBean>> map = tableHeader.get(j);
  308. Class clazz = clazzs.get(j);
  309. List objs = null;
  310. Map<String, String> resultMap = null;
  311. if (j == 0) {
  312. objs = objsMap.get("ECAT");
  313. resultMap = (Map<String, String>) resultJson.get("ECAT");
  314. } else if (j == 1) {
  315. rowindex += 5;
  316. objs = objsMap.get("EREC");
  317. resultMap = (Map<String, String>) resultJson.get("EREC");
  318. } else if (j == 2) {
  319. rowindex += 5;
  320. objs = objsMap.get("EMEM");
  321. resultMap = (Map<String, String>) resultJson.get("EMEM");
  322. }
  323. //创建标题(头)
  324. XSSFRow titleRow1 = sheet.createRow(rowindex);
  325. for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
  326. List<ExcelBean> excels = entry.getValue();
  327. for (int x = 0; x < excels.size(); x++) {
  328. XSSFCell cellTitle = titleRow1.createCell(x);
  329. cellTitle.setCellValue(excels.get(x).headTextName);
  330. cellTitle.setCellStyle(fontStyle);
  331. }
  332. }
  333. rowindex++;
  334. int maxKey = 0;
  335. List<ExcelBean> ems = new ArrayList<>();
  336. for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
  337. if (entry.getKey() > maxKey) {
  338. maxKey = entry.getKey();
  339. }
  340. }
  341. ems = map.get(maxKey);
  342. List<Integer> widths = new ArrayList<Integer>(ems.size());
  343. //渲染答题记录
  344. if (objs != null) {
  345. for (Object obj : objs) {
  346. XSSFRow row = sheet.createRow(rowindex);
  347. for (int i = 0; i < ems.size(); i++) {
  348. ExcelBean em = (ExcelBean) ems.get(i);
  349. String propertyName = em.getPropertyName();
  350. PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, clazz);
  351. Method method = propertyDescriptor.getReadMethod();
  352. Object rtn = method.invoke(obj);
  353. String value = "";
  354. // 如果是日期类型进行转换
  355. if (rtn != null) {
  356. if (rtn instanceof Date) {
  357. value = new SimpleDateFormat("yyyy-MM-dd").format(rtn);
  358. } else if (rtn instanceof BigDecimal) {
  359. NumberFormat nf = new DecimalFormat("#,##0.00");
  360. value = nf.format((BigDecimal) rtn).toString();
  361. } else if ((rtn instanceof Integer) && (Integer.valueOf(rtn.toString()) < 0)) {
  362. value = "--";
  363. } else {
  364. value = rtn.toString();
  365. }
  366. }
  367. XSSFCell cell = row.createCell(i);
  368. cell.setCellValue(value);
  369. cell.setCellType(XSSFCell.CELL_TYPE_STRING);
  370. cell.setCellStyle(fontStyle2);
  371. // 获得最大列宽
  372. int width = value.getBytes().length * 300;
  373. // 还未设置,设置当前
  374. if (widths.size() <= i) {
  375. widths.add(width);
  376. continue;
  377. }
  378. // 比原来大,更新数据
  379. if (width > widths.get(i)) {
  380. widths.set(i, width);
  381. }
  382. }
  383. rowindex++;
  384. }
  385. }
  386. rowindex += 2;
  387. if (resultMap != null && resultMap.size() > 0) {
  388. //渲染最终各项得分
  389. XSSFRow titleRow = sheet.createRow(rowindex);
  390. rowindex += 1;
  391. XSSFRow scoreRow = sheet.createRow(rowindex);
  392. int i = 0;
  393. if (resultMap.size() > 0) {
  394. for (Map.Entry<String, String> entry : resultMap.entrySet()) {
  395. XSSFCell cellTitle = titleRow.createCell(i);
  396. cellTitle.setCellValue(entry.getKey());
  397. cellTitle.setCellType(XSSFCell.CELL_TYPE_STRING);
  398. cellTitle.setCellStyle(fontStyle2);
  399. XSSFCell cellScore = scoreRow.createCell(i);
  400. cellScore.setCellValue(entry.getValue());
  401. cellScore.setCellType(XSSFCell.CELL_TYPE_STRING);
  402. cellScore.setCellStyle(fontStyle2);
  403. i++;
  404. }
  405. }
  406. }
  407. // 设置列宽
  408. for (int index = 0; index < widths.size(); index++) {
  409. Integer width = widths.get(index);
  410. width = width < 2500 ? 2500 : width + 300;
  411. width = width > 10000 ? 10000 + 300 : width + 300;
  412. sheet.setColumnWidth(index, width);
  413. }
  414. }
  415. }
  416. private static void createEALLTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, int rowindex) {
  417. ////cell起始位置
  418. //int startIndex = 0;
  419. ////cell终止位置
  420. //int endIndex = 0;
  421. //for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
  422. // XSSFRow row = sheet.createRow(entry.getKey());
  423. // List<ExcelBean> excels = entry.getValue();
  424. // for (int x = 0; x < excels.size(); x++) {
  425. // //合并单元格
  426. // //if (excels.get(x).getCols() > 1) {
  427. // if (x == 0) {
  428. // endIndex += excels.get(x).getCols() - 1;
  429. // CellRangeAddress range = new CellRangeAddress(rowindex - 1, rowindex - 1, startIndex, endIndex);
  430. // sheet.addMergedRegion(range);
  431. // } else {
  432. // endIndex += excels.get(x).getCols();
  433. // CellRangeAddress range = new CellRangeAddress(rowindex - 1, rowindex - 1, startIndex, endIndex);
  434. // sheet.addMergedRegion(range);
  435. // }
  436. // startIndex += excels.get(x).getCols();
  437. // XSSFCell cell = row.createCell(startIndex - excels.get(x).getCols());
  438. // // 设置内容
  439. // cell.setCellValue(excels.get(x).getHeadTextName());
  440. // if (excels.get(x).getCellStyle() != null) {
  441. // // 设置格式
  442. // cell.setCellStyle(excels.get(x).getCellStyle());
  443. // }
  444. // cell.setCellStyle(fontStyle);
  445. // //} else {
  446. // // XSSFCell cell = row.createCell(x);
  447. // // // 设置内容
  448. // // cell.setCellValue(excels.get(x).getHeadTextName());
  449. // // if (excels.get(x).getCellStyle() != null) {
  450. // // // 设置格式
  451. // // cell.setCellStyle(excels.get(x).getCellStyle());
  452. // // }
  453. // // cell.setCellStyle(fontStyle);
  454. // //}
  455. // }
  456. //}
  457. }
  458. /**
  459. * @param clazz
  460. * @param objs
  461. * @param resultMap
  462. * @param map
  463. * @param fileName
  464. * @return
  465. * @throws Exception
  466. */
  467. public static XSSFWorkbook createExcelFileForPublic(Class clazz, List objs, List<Map<String, String>> resultMap, Map<Integer, List<ExcelBean>> map, String fileName, String filePath) throws Exception {
  468. // 创建新的Excel工作簿
  469. XSSFWorkbook workbook = new XSSFWorkbook();
  470. // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
  471. XSSFSheet sheet = workbook.createSheet("用户信息");
  472. // 以下为excel的字体样式以及excel的标题与内容的创建,下面会具体分析;
  473. //字体样式
  474. createFont(workbook);
  475. //创建标题(头)
  476. createTableHeader(sheet, map);
  477. //创建内容
  478. createTableRows(sheet, map, objs, resultMap, clazz);
  479. String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  480. FileOutputStream fileOutputStream = null;
  481. File file = new File(filePath);
  482. if (!file.exists()) {
  483. //file.createNewFile();
  484. file.mkdirs();
  485. }
  486. fileOutputStream = new FileOutputStream(filePath + fileName);
  487. workbook.write(fileOutputStream);
  488. fileOutputStream.close();
  489. return workbook;
  490. }
  491. private static XSSFCellStyle fontStyle;
  492. private static XSSFCellStyle fontStyle2;
  493. public static void createFont(XSSFWorkbook workbook) {
  494. // 表头
  495. fontStyle = workbook.createCellStyle();
  496. XSSFFont font1 = workbook.createFont();
  497. font1.setBold(true);
  498. font1.setFontName("黑体");
  499. // 设置字体大小
  500. font1.setFontHeightInPoints((short) 14);
  501. fontStyle.setFont(font1);
  502. // 下边框
  503. fontStyle.setBorderBottom(BorderStyle.THIN);
  504. // 左边框
  505. fontStyle.setBorderLeft(BorderStyle.THIN);
  506. // 上边框
  507. fontStyle.setBorderTop(BorderStyle.THIN);
  508. // 右边框
  509. fontStyle.setBorderRight(BorderStyle.THIN);
  510. // 居中
  511. fontStyle.setAlignment(HorizontalAlignment.CENTER);
  512. // 内容
  513. fontStyle2 = workbook.createCellStyle();
  514. XSSFFont font2 = workbook.createFont();
  515. font2.setFontName("宋体");
  516. // 设置字体大小
  517. font2.setFontHeightInPoints((short) 10);
  518. fontStyle2.setFont(font2);
  519. // 下边框
  520. fontStyle2.setBorderBottom(BorderStyle.THIN);
  521. // 左边框
  522. fontStyle2.setBorderLeft(BorderStyle.THIN);
  523. // 上边框
  524. fontStyle2.setBorderTop(BorderStyle.THIN);
  525. // 右边框
  526. fontStyle2.setBorderRight(BorderStyle.THIN);
  527. // 居中
  528. fontStyle2.setAlignment(HorizontalAlignment.CENTER);
  529. }
  530. /**
  531. * 根据ExcelMapping 生成列头(多行列头)
  532. *
  533. * @param sheet 工作簿
  534. * @param map 每行每个单元格对应的列头信息
  535. */
  536. private static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) {
  537. //cell起始位置
  538. int startIndex = 0;
  539. //cell终止位置
  540. int endIndex = 0;
  541. for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
  542. XSSFRow row = sheet.createRow(entry.getKey());
  543. List<ExcelBean> excels = entry.getValue();
  544. for (int x = 0; x < excels.size(); x++) {
  545. //合并单元格
  546. if (excels.get(x).getCols() > 1) {
  547. if (x == 0) {
  548. endIndex += excels.get(x).getCols() - 1;
  549. CellRangeAddress range = new CellRangeAddress(0, 0, startIndex, endIndex);
  550. sheet.addMergedRegion(range);
  551. } else {
  552. endIndex += excels.get(x).getCols();
  553. CellRangeAddress range = new CellRangeAddress(0, 0, startIndex, endIndex);
  554. sheet.addMergedRegion(range);
  555. }
  556. startIndex += excels.get(x).getCols();
  557. XSSFCell cell = row.createCell(startIndex - excels.get(x).getCols());
  558. // 设置内容
  559. cell.setCellValue(excels.get(x).getHeadTextName());
  560. if (excels.get(x).getCellStyle() != null) {
  561. // 设置格式
  562. cell.setCellStyle(excels.get(x).getCellStyle());
  563. }
  564. cell.setCellStyle(fontStyle);
  565. } else {
  566. XSSFCell cell = row.createCell(x);
  567. // 设置内容
  568. cell.setCellValue(excels.get(x).getHeadTextName());
  569. if (excels.get(x).getCellStyle() != null) {
  570. // 设置格式
  571. cell.setCellStyle(excels.get(x).getCellStyle());
  572. }
  573. cell.setCellStyle(fontStyle);
  574. }
  575. }
  576. }
  577. }
  578. /**
  579. * @param sheet 表格sheet页
  580. * @param map 表头
  581. * @param objs 答题列表
  582. * @param clazz 量表实体类
  583. * @param resultMap 测试结果得分
  584. * @throws Exception
  585. */
  586. private static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, List<Map<String, String>> resultMap, Class clazz) throws Exception {
  587. int rowindex = map.size();
  588. int maxKey = 0;
  589. List<ExcelBean> ems = new ArrayList<>();
  590. for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
  591. if (entry.getKey() > maxKey) {
  592. maxKey = entry.getKey();
  593. }
  594. }
  595. ems = map.get(maxKey);
  596. List<Integer> widths = new ArrayList<Integer>(ems.size());
  597. //渲染答题记录
  598. if (objs != null) {
  599. for (Object obj : objs) {
  600. XSSFRow row = sheet.createRow(rowindex);
  601. for (int i = 0; i < ems.size(); i++) {
  602. ExcelBean em = (ExcelBean) ems.get(i);
  603. String propertyName = em.getPropertyName();
  604. PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, clazz);
  605. Method method = propertyDescriptor.getReadMethod();
  606. Object rtn = method.invoke(obj);
  607. String value = "";
  608. // 如果是日期类型进行转换
  609. if (rtn != null) {
  610. if (rtn instanceof Date) {
  611. value = new SimpleDateFormat("yyyy-MM-dd").format(rtn);
  612. } else if (rtn instanceof BigDecimal) {
  613. NumberFormat nf = new DecimalFormat("#,##0.00");
  614. value = nf.format((BigDecimal) rtn).toString();
  615. } else if ((rtn instanceof Integer) && (Integer.valueOf(rtn.toString()) < 0)) {
  616. value = "--";
  617. } else {
  618. value = rtn.toString();
  619. }
  620. }
  621. XSSFCell cell = row.createCell(i);
  622. cell.setCellValue(value);
  623. cell.setCellType(XSSFCell.CELL_TYPE_STRING);
  624. cell.setCellStyle(fontStyle2);
  625. // 获得最大列宽
  626. int width = value.getBytes().length * 300;
  627. // 还未设置,设置当前
  628. if (widths.size() <= i) {
  629. widths.add(width);
  630. continue;
  631. }
  632. // 比原来大,更新数据
  633. if (width > widths.get(i)) {
  634. widths.set(i, width);
  635. }
  636. }
  637. rowindex++;
  638. }
  639. }
  640. rowindex += 2;
  641. if (resultMap != null && resultMap.size() > 0) {
  642. for (int m = 0; m < resultMap.size(); m++) {
  643. Map<String, String> hashMap = resultMap.get(m);
  644. if (hashMap != null && hashMap.size() > 0) {
  645. //渲染最终各项得分
  646. XSSFRow titleRow = sheet.createRow(rowindex);
  647. rowindex += 1;
  648. XSSFRow scoreRow = sheet.createRow(rowindex);
  649. int i = 0;
  650. if (resultMap.size() > 0) {
  651. for (Map.Entry<String, String> entry : hashMap.entrySet()) {
  652. XSSFCell cellTitle = titleRow.createCell(i);
  653. cellTitle.setCellValue(entry.getKey());
  654. cellTitle.setCellType(XSSFCell.CELL_TYPE_STRING);
  655. cellTitle.setCellStyle(fontStyle2);
  656. XSSFCell cellScore = scoreRow.createCell(i);
  657. cellScore.setCellValue(entry.getValue());
  658. cellScore.setCellType(XSSFCell.CELL_TYPE_STRING);
  659. cellScore.setCellStyle(fontStyle2);
  660. i++;
  661. }
  662. }
  663. }
  664. rowindex += 2;
  665. }
  666. }
  667. // 设置列宽
  668. for (int index = 0; index < widths.size(); index++) {
  669. Integer width = widths.get(index);
  670. width = width < 2500 ? 2500 : width + 300;
  671. width = width > 10000 ? 10000 + 300 : width + 300;
  672. sheet.setColumnWidth(index, width);
  673. }
  674. }
  675. /**
  676. * 用户导入
  677. *
  678. * @param in
  679. * @param fileName
  680. * @return
  681. * @throws Exception
  682. */
  683. public static List<List<Object>> getBankListByExcelForUserImport(InputStream in, String fileName) throws Exception {
  684. List<List<Object>> list = null;
  685. //创建Excel工作薄
  686. Workbook work = getWorkbook(in, fileName);
  687. if (null == work) {
  688. throw new Exception("创建Excel工作薄为空!");
  689. }
  690. Sheet sheet = null;
  691. Row row = null;
  692. Cell cell = null;
  693. list = new ArrayList<List<Object>>();
  694. //遍历Excel中所有的sheet
  695. System.out.println("work.getNumberOfSheets():" + work.getNumberOfSheets());
  696. for (int i = 0; i < work.getNumberOfSheets(); i++) {
  697. sheet = work.getSheetAt(i);
  698. if (sheet == null) {
  699. continue;
  700. }
  701. int sheetSize = 0;
  702. //遍历当前sheet中的所有行
  703. //包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部
  704. for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
  705. //读取一行
  706. row = sheet.getRow(j);
  707. //去掉空行和表头
  708. if (row == null || row.getFirstCellNum() == j) {
  709. continue;
  710. }
  711. sheetSize = row.getLastCellNum();
  712. //判断当前行是否为空
  713. if (isRowEmpty(row)) {
  714. continue;
  715. }
  716. //遍历所有的列
  717. List<Object> li = new ArrayList<Object>();
  718. for (int y = row.getFirstCellNum(); y < sheetSize; y++) {
  719. cell = row.getCell(y);
  720. li.add(cell != null ? getCellValue(cell) : null);
  721. }
  722. list.add(li);
  723. }
  724. }
  725. return list;
  726. }
  727. /**
  728. * 判断行是否为空
  729. *
  730. * @param row 行
  731. * @return true:空 ;false:非空
  732. */
  733. public static boolean isRowEmpty(Row row) {
  734. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
  735. Cell cell = row.getCell(i);
  736. if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
  737. return false;
  738. } else {
  739. break;
  740. }
  741. }
  742. return true;
  743. }
  744. }