ExcelUtil.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package com.jkcredit.asychronous.util;
  2. import cn.afterturn.easypoi.excel.ExcelExportUtil;
  3. import cn.afterturn.easypoi.excel.entity.ExportParams;
  4. import com.alibaba.fastjson.JSONArray;
  5. import com.alibaba.fastjson.JSONObject;
  6. import com.jkcredit.asychronous.entity.Car;
  7. import com.jkcredit.asychronous.entity.ManFtpResult;
  8. import org.apache.commons.lang3.StringUtils;
  9. import org.apache.poi.hssf.usermodel.*;
  10. import org.apache.poi.ss.usermodel.*;
  11. import org.apache.poi.ss.util.CellRangeAddress;
  12. import org.apache.poi.xssf.streaming.SXSSFCell;
  13. import org.apache.poi.xssf.streaming.SXSSFRow;
  14. import org.apache.poi.xssf.streaming.SXSSFSheet;
  15. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  16. import org.apache.poi.xssf.usermodel.XSSFCell;
  17. import org.apache.poi.xssf.usermodel.XSSFRow;
  18. import org.apache.poi.xssf.usermodel.XSSFSheet;
  19. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  20. import java.io.*;
  21. import java.math.BigDecimal;
  22. import java.text.SimpleDateFormat;
  23. import java.util.*;
  24. import static javax.print.attribute.standard.JobState.PROCESSING;
  25. import static javax.xml.bind.JAXBIntrospector.getValue;
  26. /**
  27. * @Descirption
  28. * @Author Zhaoning Sun
  29. * @Date Created in 2018/6/22 下午5:53
  30. */
  31. public class ExcelUtil {
  32. /**
  33. * suffix of excel 2003
  34. */
  35. public static final String OFFICE_EXCEL_V2003_SUFFIX = "xls";
  36. /**
  37. * suffix of excel 2007
  38. */
  39. public static final String OFFICE_EXCEL_V2007_SUFFIX = "xlsx";
  40. /**
  41. * suffix of excel 2010
  42. */
  43. public static final String OFFICE_EXCEL_V2010_SUFFIX = "xlsx";
  44. public static final String NOT_EXCEL_FILE = " is Not a Excel file!";
  45. public static final String EMPTY = "";
  46. public static final String DOT = ".";
  47. public static String NO_DEFINE = "no_define";//未定义的字段
  48. public static String DEFAULT_DATE_PATTERN="yyyy年MM月dd日";//默认日期格式
  49. public static int DEFAULT_COLOUMN_WIDTH = 17;
  50. public static <T> String export(List<T> list, Class<T> clazz, String pathName,String time) {
  51. File savefile = new File(pathName);
  52. if (!savefile.exists()) {
  53. savefile.mkdirs();
  54. }
  55. Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),
  56. clazz, list);
  57. FileOutputStream fos;
  58. try {
  59. String fileName = pathName + File.separator + time + ".xls";
  60. fos = new FileOutputStream(fileName);
  61. workbook.write(fos);
  62. fos.close();
  63. return fileName;
  64. } catch (Exception e) {
  65. e.printStackTrace();
  66. }
  67. return null;
  68. }
  69. public static List<ManFtpResult> readExcel(String path) {
  70. if (StringUtils.isBlank(path)) {
  71. throw new IllegalArgumentException(path + " excel file path is either null or empty");
  72. } else {
  73. String suffiex = getSuffiex(path);
  74. if(StringUtils.isBlank(suffiex)){
  75. throw new IllegalArgumentException(path + " suffiex is either null or empty");
  76. }
  77. if (OFFICE_EXCEL_V2003_SUFFIX.equals(suffiex)) {
  78. return readXls(path);
  79. } else if (OFFICE_EXCEL_V2007_SUFFIX.equals(suffiex)) {
  80. return readXlsx(path);
  81. } else if (OFFICE_EXCEL_V2010_SUFFIX.equals(suffiex)) {
  82. return readXlsx(path);
  83. } else {
  84. throw new IllegalArgumentException(path + NOT_EXCEL_FILE);
  85. }
  86. }
  87. }
  88. public static List<ManFtpResult> readXls(String path) {
  89. InputStream is = null;
  90. HSSFWorkbook hssfWorkbook = null;
  91. List<ManFtpResult> list = new ArrayList<ManFtpResult>();
  92. try {
  93. is = new FileInputStream(path);
  94. hssfWorkbook= new HSSFWorkbook(is);
  95. ManFtpResult manFtpResult = null;
  96. // Read the Sheet
  97. for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
  98. HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
  99. if (hssfSheet == null) {
  100. continue;
  101. }
  102. // Read the Row
  103. for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
  104. HSSFRow hssfRow = hssfSheet.getRow(rowNum);
  105. if (hssfRow != null) {
  106. manFtpResult = new ManFtpResult();
  107. HSSFCell id = hssfRow.getCell(0);
  108. HSSFCell name = hssfRow.getCell(1);
  109. HSSFCell idCard = hssfRow.getCell(2);
  110. HSSFCell isIdCard = hssfRow.getCell(3);
  111. HSSFCell isEscape = hssfRow.getCell(4);
  112. HSSFCell isPedigree = hssfRow.getCell(5);
  113. HSSFCell isDrugs = hssfRow.getCell(6);
  114. manFtpResult.setManId(getValue(id).toString());
  115. manFtpResult.setName(getValue(name).toString());
  116. manFtpResult.setIdCard(getValue(idCard).toString());
  117. manFtpResult.setIsIdCard(getValue(isIdCard).toString());
  118. manFtpResult.setIsEscape(getValue(isEscape).toString());
  119. manFtpResult.setIsPedigree(getValue(isPedigree).toString());
  120. manFtpResult.setIsDrugs(getValue(isDrugs).toString());
  121. list.add(manFtpResult);
  122. }
  123. }
  124. }
  125. } catch (FileNotFoundException e) {
  126. e.printStackTrace();
  127. } catch (IOException e) {
  128. e.printStackTrace();
  129. }
  130. return list;
  131. }
  132. public static List<ManFtpResult> readXlsx(String path){
  133. InputStream is;
  134. XSSFWorkbook xssfWorkbook = null;
  135. try {
  136. is = new FileInputStream(path);
  137. xssfWorkbook = new XSSFWorkbook(is);
  138. } catch (IOException e) {
  139. e.printStackTrace();
  140. }
  141. ManFtpResult manFtpResult = null;
  142. List<ManFtpResult> list = new ArrayList<ManFtpResult>();
  143. // Read the Sheet
  144. for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
  145. XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
  146. if (xssfSheet == null) {
  147. continue;
  148. }
  149. // Read the Row
  150. for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
  151. XSSFRow xssfRow = xssfSheet.getRow(rowNum);
  152. if (xssfRow != null) {
  153. manFtpResult = new ManFtpResult();
  154. XSSFCell id = xssfRow.getCell(0);
  155. XSSFCell name = xssfRow.getCell(1);
  156. XSSFCell idCard = xssfRow.getCell(2);
  157. XSSFCell isIdCard = xssfRow.getCell(3);
  158. XSSFCell isEscape = xssfRow.getCell(4);
  159. XSSFCell isPedigree = xssfRow.getCell(5);
  160. XSSFCell isDrugs = xssfRow.getCell(6);
  161. manFtpResult.setManId(getValue(id).toString());
  162. manFtpResult.setName(getValue(name).toString());
  163. manFtpResult.setIdCard(getValue(idCard).toString());
  164. manFtpResult.setIsIdCard(getValue(isIdCard).toString());
  165. manFtpResult.setIsEscape(getValue(isEscape).toString());
  166. manFtpResult.setIsPedigree(getValue(isPedigree).toString());
  167. manFtpResult.setIsDrugs(getValue(isDrugs).toString());
  168. list.add(manFtpResult);
  169. }
  170. }
  171. }
  172. return list;
  173. }
  174. public static String getSuffiex(String path) {
  175. if(StringUtils.isBlank(path)){
  176. return EMPTY;
  177. }
  178. int index = path.lastIndexOf(DOT);
  179. if (index == -1) {
  180. return EMPTY;
  181. }
  182. return path.substring(index + 1, path.length());
  183. }
  184. /**
  185. * 导出Excel 2007 OOXML (.xlsx)格式
  186. * @param headMap 属性-列头
  187. * @param jsonArray 数据集
  188. * @param datePattern 日期格式,传null值则默认 年月日
  189. * @param colWidth 列宽 默认 至少17个字节
  190. * @param out 输出流
  191. */
  192. public static void exportExcelX( Map<String, String> headMap, JSONArray jsonArray, String datePattern,
  193. int colWidth, OutputStream out) {
  194. if (datePattern == null){
  195. datePattern = DEFAULT_DATE_PATTERN;
  196. }
  197. // 声明一个工作薄 缓存
  198. SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
  199. workbook.setCompressTempFiles(true);
  200. //表头样式
  201. CellStyle titleStyle = workbook.createCellStyle();
  202. titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  203. Font titleFont = workbook.createFont();
  204. titleFont.setFontHeightInPoints((short) 20);
  205. titleFont.setBoldweight((short) 700);
  206. titleStyle.setFont(titleFont);
  207. // 列头样式
  208. // CellStyle headerStyle = workbook.createCellStyle();
  209. // headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  210. // headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  211. // headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  212. // headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  213. // headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  214. // headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  215. // Font headerFont = workbook.createFont();
  216. // headerFont.setFontHeightInPoints((short) 12);
  217. // headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  218. // headerStyle.setFont(headerFont);
  219. // 单元格样式
  220. // CellStyle cellStyle = workbook.createCellStyle();
  221. // cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  222. // cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  223. // cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  224. // cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  225. // cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  226. // cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  227. // cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  228. // Font cellFont = workbook.createFont();
  229. // cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  230. // cellStyle.setFont(cellFont);
  231. // 生成一个(带标题)表格
  232. SXSSFSheet sheet = workbook.createSheet();
  233. //设置列宽
  234. int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;//至少字节数
  235. int[] arrColWidth = new int[headMap.size()];
  236. // 产生表格标题行,以及设置列宽
  237. String[] properties = new String[headMap.size()];
  238. String[] headers = new String[headMap.size()];
  239. int ii = 0;
  240. for (Iterator<String> iter = headMap.keySet().iterator(); iter
  241. .hasNext(); ) {
  242. String fieldName = iter.next();
  243. properties[ii] = fieldName;
  244. headers[ii] = headMap.get(fieldName);
  245. int bytes = fieldName.getBytes().length;
  246. arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
  247. sheet.setColumnWidth(ii, arrColWidth[ii] * 256);
  248. ii++;
  249. }
  250. // 遍历集合数据,产生数据行
  251. int rowIndex = 0;
  252. for (Object obj : jsonArray) {
  253. if (rowIndex == 65535 || rowIndex == 0) {
  254. if (rowIndex != 0) {
  255. sheet = workbook.createSheet();//如果数据超过了,则在第二页显示
  256. }
  257. // SXSSFRow titleRow = sheet.createRow(0);//表头 rowIndex=0
  258. // titleRow.createCell(0).setCellValue(title);
  259. // titleRow.getCell(0).setCellStyle(titleStyle);
  260. // sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));
  261. // SXSSFRow headerRow = sheet.createRow(0); //列头 rowIndex =1
  262. // for (int i = 0; i < headers.length; i++) {
  263. // headerRow.createCell(i).setCellValue(headers[i]);
  264. // headerRow.getCell(i).setCellStyle(headerStyle);
  265. //
  266. // }
  267. rowIndex = 0;//数据内容从 rowIndex=2开始
  268. }
  269. JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
  270. SXSSFRow dataRow = sheet.createRow(rowIndex);
  271. for (int i = 0; i < properties.length; i++) {
  272. SXSSFCell newCell = dataRow.createCell(i);
  273. Object o = jo.get(properties[i]);
  274. String cellValue = "";
  275. if (o == null) {
  276. cellValue = "";
  277. } else if (o instanceof Date) {
  278. cellValue = new SimpleDateFormat(datePattern).format(o);
  279. } else if (o instanceof Float || o instanceof Double) {
  280. cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
  281. } else {
  282. cellValue = o.toString();
  283. }
  284. newCell.setCellValue(cellValue);
  285. // newCell.setCellStyle(cellStyle);
  286. }
  287. rowIndex++;
  288. }
  289. // 自动调整宽度
  290. /*for (int i = 0; i < headers.length; i++) {
  291. sheet.autoSizeColumn(i);
  292. }*/
  293. try {
  294. workbook.write(out);
  295. workbook.close();
  296. workbook.dispose();
  297. } catch (IOException e) {
  298. e.printStackTrace();
  299. }
  300. }
  301. }