ReportExcelUtil.java 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package com.minpay.dianwang.util;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.math.BigInteger;
  10. import java.net.URLEncoder;
  11. import java.util.Collection;
  12. import java.util.Iterator;
  13. import java.util.List;
  14. import java.util.Map;
  15. import javax.servlet.http.HttpServletResponse;
  16. import org.apache.poi.hssf.usermodel.HSSFCell;
  17. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  18. import org.apache.poi.hssf.usermodel.HSSFRow;
  19. import org.apache.poi.hssf.usermodel.HSSFSheet;
  20. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  21. import org.apache.poi.ss.usermodel.Font;
  22. import org.apache.poi.ss.util.CellRangeAddress;
  23. import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
  24. import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
  25. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  26. import org.apache.poi.xwpf.usermodel.XWPFParagraph;
  27. import org.apache.poi.xwpf.usermodel.XWPFRun;
  28. import org.apache.poi.xwpf.usermodel.XWPFTable;
  29. import org.apache.poi.xwpf.usermodel.XWPFTableRow;
  30. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
  31. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;
  32. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
  33. import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd;
  34. import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
  35. import com.minpay.common.util.CommonUtil;
  36. import net.sf.json.JSONArray;
  37. /**
  38. * 基于POI的javaEE导出Excel工具类
  39. * @author zhumq
  40. * @see POI
  41. */
  42. public class ReportExcelUtil {
  43. /**
  44. * @param response 请求
  45. * @param fileName 文件名 如:"财务报表"
  46. * @param excelHeader excel表头数组,存放"姓名#name"格式字符串,"姓名"为excel标题行, "name"为对象字段名
  47. * @param dataList 数据集合,需与表头数组中的字段名一致,并且符合javaBean规范
  48. * @return 返回一个HSSFWorkbook
  49. * @throws Exception
  50. */
  51. public static <T> HSSFWorkbook export(HttpServletResponse response, String fileName,
  52. List<List<String>> dataList, String reportDesc) throws Exception {
  53. // 设置请求
  54. response.setContentType("application/application/vnd.ms-excel");
  55. response.setHeader("Content-disposition",
  56. "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
  57. // 创建一个Workbook,对应一个Excel文件
  58. HSSFWorkbook wb = new HSSFWorkbook();
  59. // 在Workbook中添加一个sheet,对应Excel文件中的sheet
  60. HSSFSheet sheet = wb.createSheet(fileName);
  61. // 遍历集合数据,产生数据行
  62. int index = 0;
  63. if (!CommonUtil.isEmpty(reportDesc)) {
  64. HSSFRow row = sheet.createRow(index);
  65. row.setHeight((short)1000);
  66. HSSFCell dataCell = row.createCell(0);
  67. dataCell.setCellValue(reportDesc);
  68. CellRangeAddress region = new CellRangeAddress(0, 0, 0, dataList.get(0).size() - 1);
  69. sheet.addMergedRegion(region);
  70. index ++;
  71. }
  72. for (Object dataChild : dataList) {
  73. List<Object> dataChildList = (List<Object>)dataChild;
  74. HSSFRow row = sheet.createRow(index);
  75. for (int i = 0; i < dataChildList.size(); i ++) {
  76. String data = CommonUtil.objToString(dataChildList.get(i));
  77. HSSFCell dataCell = row.createCell(i);
  78. dataCell.setCellValue(data);
  79. }
  80. index ++;
  81. }
  82. // sheet.setColumnWidth(fieldArray.length, 20 * 256);
  83. return wb;
  84. }
  85. public static <T> HSSFWorkbook export(HttpServletResponse response, String fileName, String[] excelHeader,
  86. Collection<T> dataList) throws Exception {
  87. // 设置请求
  88. response.setContentType("application/application/vnd.ms-excel");
  89. response.setHeader("Content-disposition",
  90. "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
  91. // 创建一个Workbook,对应一个Excel文件
  92. HSSFWorkbook wb = new HSSFWorkbook();
  93. // 设置标题样式
  94. HSSFCellStyle titleStyle = wb.createCellStyle();
  95. // 设置字体样式
  96. Font titleFont = wb.createFont();
  97. titleFont.setFontHeightInPoints((short) 12); // 字体高度
  98. titleFont.setFontName("黑体"); // 字体样式
  99. titleStyle.setFont(titleFont);
  100. // 在Workbook中添加一个sheet,对应Excel文件中的sheet
  101. HSSFSheet sheet = wb.createSheet(fileName);
  102. // 标题数组
  103. String[] titleArray = new String[excelHeader.length];
  104. // 字段名数组
  105. String[] fieldArray = new String[excelHeader.length];
  106. for (int i = 0; i < excelHeader.length; i++) {
  107. String[] tempArray = excelHeader[i].split("#");// 临时数组 分割#
  108. titleArray[i] = tempArray[0];
  109. fieldArray[i] = tempArray[1];
  110. }
  111. // 在sheet中添加标题行
  112. HSSFRow row = sheet.createRow((int) 0);// 行数从0开始
  113. HSSFCell sequenceCell = row.createCell(0);// cell列 从0开始 第一列添加序号
  114. sequenceCell.setCellValue("序号");
  115. sequenceCell.setCellStyle(titleStyle);
  116. sheet.autoSizeColumn(0);// 自动设置宽度
  117. // 为标题行赋值
  118. for (int i = 0; i < titleArray.length; i++) {
  119. HSSFCell titleCell = row.createCell(i + 1);// 0号位被序号占用,所以需+1
  120. titleCell.setCellValue(titleArray[i]);
  121. titleCell.setCellStyle(titleStyle);
  122. sheet.autoSizeColumn(i + 1);// 0号位被序号占用,所以需+1
  123. sheet.setColumnWidth(i+1,titleArray[i].getBytes().length*256+200);
  124. }
  125. // 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖
  126. HSSFCellStyle dataStyle = wb.createCellStyle();
  127. // 设置数据字体
  128. Font dataFont = wb.createFont();
  129. dataFont.setFontHeightInPoints((short) 10); // 字体高度
  130. dataFont.setFontName("宋体"); // 字体
  131. dataStyle.setFont(dataFont);
  132. // 遍历集合数据,产生数据行
  133. Iterator<T> it = dataList.iterator();
  134. int index = 0;
  135. while (it.hasNext()) {
  136. index++;
  137. row = sheet.createRow(index);
  138. // 为序号赋值
  139. HSSFCell sequenceCellValue = row.createCell(0);// 序号值永远是第0列
  140. sequenceCellValue.setCellValue(index);
  141. sequenceCellValue.setCellStyle(dataStyle);
  142. // sheet.autoSizeColumn(0);
  143. T t = (T) it.next();
  144. Map<String, Object> map = (Map<String, Object> )t;
  145. HSSFCell dataCell = null;
  146. for (int i = 0; i < fieldArray.length; i++) {
  147. dataCell = row.createCell(i + 1);
  148. dataCell.setCellStyle(dataStyle);
  149. String fieldName = fieldArray[i];
  150. String value = CommonUtil.objToString(map.get(fieldName));
  151. if (CommonUtil.isEmpty(value)) {
  152. dataCell.setCellValue(""); // 为当前列赋值
  153. } else {
  154. dataCell.setCellValue(CommonUtil.objToString(value));// 为当前列赋值
  155. }
  156. }
  157. }
  158. sheet.setColumnWidth(fieldArray.length, 20 * 256);
  159. return wb;
  160. }
  161. public static void write2Docx(HttpServletResponse response, String title, String content, String path, String fileName)throws Exception{
  162. XWPFDocument document= new XWPFDocument();
  163. //Write the Document in file system
  164. File saveFilePath = new File(path);
  165. if (!saveFilePath.exists()) {
  166. saveFilePath.mkdirs();
  167. }
  168. FileOutputStream out = null;
  169. try {
  170. out = new FileOutputStream(new File(path + "\\" + fileName));
  171. //添加标题
  172. XWPFParagraph titleParagraph = document.createParagraph();
  173. //设置段落居中
  174. titleParagraph.setAlignment(ParagraphAlignment.CENTER);
  175. XWPFRun titleParagraphRun = titleParagraph.createRun();
  176. titleParagraphRun.setText(title);
  177. titleParagraphRun.setColor("000000");
  178. titleParagraphRun.setFontSize(20);
  179. String[] paragraphs = content.split(System.getProperty("line.separator"));
  180. for (int i = 0; i < paragraphs.length; i ++) {
  181. //段落
  182. XWPFParagraph firstParagraph = document.createParagraph();
  183. XWPFRun run = firstParagraph.createRun();
  184. run.setText(paragraphs[i]);
  185. run.setColor("696969");
  186. run.setFontSize(16);
  187. }
  188. document.write(out);
  189. } catch (Exception e) {
  190. e.printStackTrace();
  191. } finally {
  192. out.close();
  193. }
  194. OutputStream toClient = null;
  195. InputStream fis = null;
  196. try {
  197. fis = new BufferedInputStream(new FileInputStream(path + "\\" + fileName));
  198. byte[] buffer = new byte[fis.available()];
  199. fis.read(buffer);
  200. // 清空response
  201. response.reset();
  202. // 设置response的Header
  203. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  204. toClient = new BufferedOutputStream(response.getOutputStream());
  205. response.setContentType("application/octet-stream");
  206. toClient.write(buffer);
  207. toClient.flush();
  208. } catch (Exception e) {
  209. e.printStackTrace();
  210. } finally {
  211. fis.close();
  212. toClient.close();
  213. }
  214. // 操作成功后删除本地文件
  215. new File(path + "\\" + fileName).delete();
  216. }
  217. }