de8a5906af8d7a8066027b8fc5c3d16dd6dd5354.svn-base 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. package cn.com.goldenwater.dcproj.utils;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import org.apache.poi.hpsf.SummaryInformation;
  5. import org.apache.poi.hssf.usermodel.*;
  6. import org.apache.poi.hssf.util.HSSFColor;
  7. import org.apache.poi.ss.usermodel.*;
  8. import org.apache.poi.ss.util.CellRangeAddress;
  9. import org.apache.poi.xssf.streaming.SXSSFCell;
  10. import org.apache.poi.xssf.streaming.SXSSFRow;
  11. import org.apache.poi.xssf.streaming.SXSSFSheet;
  12. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  13. import javax.servlet.ServletOutputStream;
  14. import javax.servlet.http.HttpServletResponse;
  15. import java.io.*;
  16. import java.math.BigDecimal;
  17. import java.text.SimpleDateFormat;
  18. import java.util.Date;
  19. import java.util.Iterator;
  20. import java.util.Map;
  21. /**
  22. * @ClassName ExcelUtils
  23. * @Description 导出Excel的工具类
  24. * @Author liyz
  25. * @Date 2019/3/6 9:43
  26. * @Version 1.0
  27. **/
  28. public class ExcelUtils {
  29. /**
  30. * 未定义的字段
  31. */
  32. public static final String NO_DEFINE = "no_define";
  33. /**
  34. * 默认日期格式
  35. */
  36. public static final String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日";
  37. /**
  38. * 默认列宽
  39. */
  40. public static final int DEFAULT_COLOUMN_WIDTH = 17;
  41. /**
  42. * 导出Excel 97(.xls)格式 ,少量数据
  43. *
  44. * @param title 标题行
  45. * @param headMap 属性-列名
  46. * @param jsonArray 数据集
  47. * @param datePattern 日期格式,null则用默认日期格式
  48. * @param colWidth 列宽 默认 至少17个字节
  49. * @param out 输出流
  50. */
  51. public static void exportExcel(String title, Map<String, String> headMap, JSONArray jsonArray, String datePattern, int colWidth, OutputStream out) {
  52. if (datePattern == null) {
  53. datePattern = DEFAULT_DATE_PATTERN;
  54. }
  55. ;
  56. // 声明一个工作薄
  57. HSSFWorkbook workbook = new HSSFWorkbook();
  58. workbook.createInformationProperties();
  59. workbook.getDocumentSummaryInformation().setCompany("*****公司");
  60. SummaryInformation si = workbook.getSummaryInformation();
  61. //填加xls文件作者信息
  62. si.setAuthor("JACK");
  63. //填加xls文件创建程序信息
  64. si.setApplicationName("导出程序");
  65. //填加xls文件最后保存者信息
  66. si.setLastAuthor("最后保存者信息");
  67. //填加xls文件作者信息
  68. si.setComments("JACK is a programmer!");
  69. //填加xls文件标题信息
  70. si.setTitle("POI导出Excel");
  71. //填加文件主题信息
  72. si.setSubject("POI导出Excel");
  73. si.setCreateDateTime(new Date());
  74. //表头样式
  75. HSSFCellStyle titleStyle = workbook.createCellStyle();
  76. titleStyle.setAlignment(HorizontalAlignment.CENTER);
  77. HSSFFont titleFont = workbook.createFont();
  78. titleFont.setFontHeightInPoints((short) 20);
  79. // titleFont.setBoldweight((short) 700);
  80. titleFont.setBold(true);
  81. titleStyle.setFont(titleFont);
  82. // 列头样式
  83. HSSFCellStyle headerStyle = workbook.createCellStyle();
  84. headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  85. headerStyle.setBorderBottom(BorderStyle.THIN);
  86. headerStyle.setBorderLeft(BorderStyle.THIN);
  87. headerStyle.setBorderRight(BorderStyle.THIN);
  88. headerStyle.setBorderTop(BorderStyle.THIN);
  89. headerStyle.setAlignment(HorizontalAlignment.CENTER);
  90. HSSFFont headerFont = workbook.createFont();
  91. headerFont.setFontHeightInPoints((short) 12);
  92. // headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  93. headerFont.setBold(true);
  94. headerStyle.setFont(headerFont);
  95. // 单元格样式
  96. HSSFCellStyle cellStyle = workbook.createCellStyle();
  97. cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  98. cellStyle.setBorderBottom(BorderStyle.THIN);
  99. cellStyle.setBorderLeft(BorderStyle.THIN);
  100. cellStyle.setBorderRight(BorderStyle.THIN);
  101. cellStyle.setBorderTop(BorderStyle.THIN);
  102. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  103. cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  104. HSSFFont cellFont = workbook.createFont();
  105. // cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  106. cellFont.setBold(true);
  107. cellStyle.setFont(cellFont);
  108. // 生成一个(带标题)表格
  109. HSSFSheet sheet = workbook.createSheet();
  110. // 声明一个画图的顶级管理器
  111. HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
  112. // 定义注释的大小和位置,详见文档
  113. HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
  114. 0, 0, 0, (short) 4, 2, (short) 6, 5));
  115. // 设置注释内容
  116. comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
  117. // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
  118. comment.setAuthor("JACK");
  119. //设置列宽
  120. //至少字节数
  121. int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;
  122. int[] arrColWidth = new int[headMap.size()];
  123. // 产生表格标题行,以及设置列宽
  124. String[] properties = new String[headMap.size()];
  125. String[] headers = new String[headMap.size()];
  126. int ii = 0;
  127. for (Iterator<String> iter = headMap.keySet().iterator(); iter
  128. .hasNext(); ) {
  129. String fieldName = iter.next();
  130. properties[ii] = fieldName;
  131. headers[ii] = fieldName;
  132. int bytes = fieldName.getBytes().length;
  133. arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
  134. sheet.setColumnWidth(ii, arrColWidth[ii] * 256);
  135. ii++;
  136. }
  137. // 遍历集合数据,产生数据行
  138. int rowIndex = 0;
  139. for (Object obj : jsonArray) {
  140. if (rowIndex == 65535 || rowIndex == 0) {
  141. //如果数据超过了,则在第二页显示
  142. if (rowIndex != 0) {
  143. sheet = workbook.createSheet();
  144. }
  145. //表头 rowIndex=0
  146. HSSFRow titleRow = sheet.createRow(0);
  147. titleRow.createCell(0).setCellValue(title);
  148. titleRow.getCell(0).setCellStyle(titleStyle);
  149. sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));
  150. //列头 rowIndex =1
  151. HSSFRow headerRow = sheet.createRow(1);
  152. for (int i = 0; i < headers.length; i++) {
  153. headerRow.createCell(i).setCellValue(headers[i]);
  154. headerRow.getCell(i).setCellStyle(headerStyle);
  155. }
  156. //数据内容从 rowIndex=2开始
  157. rowIndex = 2;
  158. }
  159. JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
  160. HSSFRow dataRow = sheet.createRow(rowIndex);
  161. for (int i = 0; i < properties.length; i++) {
  162. HSSFCell newCell = dataRow.createCell(i);
  163. Object o = jo.get(properties[i]);
  164. String cellValue = "";
  165. if (o == null) {
  166. cellValue = "";
  167. } else if (o instanceof Date) {
  168. cellValue = new SimpleDateFormat(datePattern).format(o);
  169. } else {
  170. cellValue = o.toString();
  171. }
  172. newCell.setCellValue(cellValue);
  173. newCell.setCellStyle(cellStyle);
  174. }
  175. rowIndex++;
  176. }
  177. try {
  178. workbook.write(out);
  179. workbook.close();
  180. } catch (IOException e) {
  181. e.printStackTrace();
  182. }
  183. }
  184. /**
  185. * 导出Excel 2007 OOXML (.xlsx)格式
  186. *
  187. * @param title 标题行
  188. * @param headMap 属性-列头
  189. * @param jsonArray 数据集
  190. * @param datePattern 日期格式,传null值则默认 年月日
  191. * @param colWidth 列宽 默认 至少17个字节
  192. * @param out 输出流
  193. */
  194. public static void exportExcelX(String title, Map<String, String> headMap, JSONArray jsonArray, String datePattern, int colWidth, OutputStream out) {
  195. if (datePattern == null) {
  196. datePattern = DEFAULT_DATE_PATTERN;
  197. }
  198. // 声明一个工作薄
  199. //缓存
  200. SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
  201. workbook.setCompressTempFiles(true);
  202. //表头样式
  203. CellStyle titleStyle = workbook.createCellStyle();
  204. titleStyle.setAlignment(HorizontalAlignment.CENTER);
  205. Font titleFont = workbook.createFont();
  206. titleFont.setFontHeightInPoints((short) 20);
  207. // titleFont.setBoldweight((short) 700);
  208. titleFont.setBold(true);
  209. titleStyle.setFont(titleFont);
  210. // 列头样式
  211. CellStyle headerStyle = workbook.createCellStyle();
  212. headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  213. headerStyle.setBorderBottom(BorderStyle.THIN);
  214. headerStyle.setBorderLeft(BorderStyle.THIN);
  215. headerStyle.setBorderRight(BorderStyle.THIN);
  216. headerStyle.setBorderTop(BorderStyle.THIN);
  217. headerStyle.setAlignment(HorizontalAlignment.CENTER);
  218. headerStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.index);
  219. Font headerFont = workbook.createFont();
  220. headerFont.setFontHeightInPoints((short) 12);
  221. // headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  222. headerFont.setBold(true);
  223. headerStyle.setFont(headerFont);
  224. // 单元格样式
  225. CellStyle cellStyle = workbook.createCellStyle();
  226. cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  227. cellStyle.setBorderBottom(BorderStyle.THIN);
  228. cellStyle.setBorderLeft(BorderStyle.THIN);
  229. cellStyle.setBorderRight(BorderStyle.THIN);
  230. cellStyle.setBorderTop(BorderStyle.THIN);
  231. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  232. cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.index);
  233. cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  234. Font cellFont = workbook.createFont();
  235. // cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  236. cellFont.setBold(true);
  237. cellStyle.setFont(cellFont);
  238. // 生成一个(带标题)表格
  239. SXSSFSheet sheet = workbook.createSheet();
  240. //设置列宽
  241. //至少字节数
  242. int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;
  243. int[] arrColWidth = new int[headMap.size()];
  244. // 产生表格标题行,以及设置列宽
  245. String[] properties = new String[headMap.size()];
  246. String[] headers = new String[headMap.size()];
  247. int ii = 0;
  248. for (Iterator<String> iter = headMap.keySet().iterator(); iter
  249. .hasNext(); ) {
  250. String fieldName = iter.next();
  251. properties[ii] = fieldName;
  252. headers[ii] = headMap.get(fieldName);
  253. int bytes = fieldName.getBytes().length;
  254. arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
  255. sheet.setColumnWidth(ii, arrColWidth[ii] * 256);
  256. ii++;
  257. }
  258. // 遍历集合数据,产生数据行
  259. int rowIndex = 0;
  260. for (Object obj : jsonArray) {
  261. if (rowIndex == 65535 || rowIndex == 0) {
  262. if (rowIndex != 0) {
  263. //如果数据超过了,则在第二页显示
  264. sheet = workbook.createSheet();
  265. }
  266. //表头 rowIndex=0
  267. SXSSFRow titleRow = sheet.createRow(0);
  268. titleRow.createCell(0).setCellValue(title);
  269. titleRow.getCell(0).setCellStyle(titleStyle);
  270. sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));
  271. //列头 rowIndex =1
  272. SXSSFRow headerRow = sheet.createRow(1);
  273. for (int i = 0; i < headers.length; i++) {
  274. headerRow.createCell(i).setCellValue(headers[i]);
  275. headerRow.getCell(i).setCellStyle(headerStyle);
  276. }
  277. //数据内容从 rowIndex=2开始
  278. rowIndex = 2;
  279. }
  280. JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
  281. SXSSFRow dataRow = sheet.createRow(rowIndex);
  282. for (int i = 0; i < properties.length; i++) {
  283. SXSSFCell newCell = dataRow.createCell(i);
  284. Object o = jo.get(properties[i]);
  285. String cellValue = "";
  286. if (o == null) {
  287. cellValue = "";
  288. } else if (o instanceof Date) {
  289. cellValue = new SimpleDateFormat(datePattern).format(o);
  290. } else if (o instanceof Float || o instanceof Double) {
  291. cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
  292. } else {
  293. cellValue = o.toString();
  294. }
  295. newCell.setCellValue(cellValue);
  296. newCell.setCellStyle(cellStyle);
  297. }
  298. rowIndex++;
  299. }
  300. try {
  301. workbook.write(out);
  302. workbook.close();
  303. workbook.dispose();
  304. } catch (IOException e) {
  305. e.printStackTrace();
  306. }
  307. }
  308. /**
  309. * Web 导出excel
  310. */
  311. public static void downloadExcelFile(String title, Map<String, String> headMap, JSONArray ja, HttpServletResponse response) {
  312. try {
  313. ByteArrayOutputStream os = new ByteArrayOutputStream();
  314. ExcelUtils.exportExcelX(title, headMap, ja, null, 0, os);
  315. byte[] content = os.toByteArray();
  316. InputStream is = new ByteArrayInputStream(content);
  317. // 设置response参数,可以打开下载页面
  318. response.reset();
  319. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
  320. response.setHeader("Content-Disposition", "attachment;filename=" + new String((title + ".xlsx").getBytes(), "iso-8859-1"));
  321. response.setContentLength(content.length);
  322. ServletOutputStream outputStream = response.getOutputStream();
  323. BufferedInputStream bis = new BufferedInputStream(is);
  324. BufferedOutputStream bos = new BufferedOutputStream(outputStream);
  325. byte[] buff = new byte[8192];
  326. int bytesRead;
  327. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  328. bos.write(buff, 0, bytesRead);
  329. }
  330. bis.close();
  331. bos.close();
  332. outputStream.flush();
  333. outputStream.close();
  334. } catch (Exception e) {
  335. e.printStackTrace();
  336. }
  337. }
  338. /**
  339. * 下载Excel重载方法
  340. */
  341. public static void downloadExcelFile(HttpServletResponse response, ByteArrayOutputStream os, String fileName) {
  342. try {
  343. byte[] content = os.toByteArray();
  344. InputStream is = new ByteArrayInputStream(content);
  345. // 设置response参数,可以打开下载页面
  346. response.reset();
  347. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
  348. response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
  349. response.setContentLength(content.length);
  350. ServletOutputStream outputStream = response.getOutputStream();
  351. BufferedInputStream bis = new BufferedInputStream(is);
  352. BufferedOutputStream bos = new BufferedOutputStream(outputStream);
  353. byte[] buff = new byte[8192];
  354. int bytesRead;
  355. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  356. bos.write(buff, 0, bytesRead);
  357. }
  358. bis.close();
  359. bos.close();
  360. outputStream.flush();
  361. outputStream.close();
  362. } catch (Exception e) {
  363. e.printStackTrace();
  364. }
  365. }
  366. }