ExcelUtils.java 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package com.zhcs.dt.service.information.annualPlan;
  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.net.URLEncoder;
  10. import java.util.List;
  11. import javax.servlet.http.HttpServletResponse;
  12. import org.apache.poi.ss.usermodel.BorderStyle;
  13. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  14. import org.apache.poi.ss.usermodel.IndexedColors;
  15. import org.apache.poi.ss.usermodel.VerticalAlignment;
  16. import org.apache.poi.ss.util.CellRangeAddress;
  17. import org.apache.poi.xssf.usermodel.XSSFCell;
  18. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  19. import org.apache.poi.xssf.usermodel.XSSFRow;
  20. import org.apache.poi.xssf.usermodel.XSSFSheet;
  21. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  22. import org.springframework.stereotype.Component;
  23. import com.zhcs.dt.util.PageData;
  24. @Component
  25. public class ExcelUtils {
  26. /**
  27. *tempPath 模板文件路径
  28. *path 文件路径
  29. *list 集合数据
  30. */
  31. public void exportExcel(String fileName, String path, HttpServletResponse response, List<PageData> list,String keyStr) {
  32. String tempPath = path + "\\" + fileName;
  33. File newFile = createNewFile(tempPath, path);
  34. InputStream is = null;
  35. XSSFWorkbook workbook = null;
  36. XSSFSheet sheet = null;
  37. try {
  38. is = new FileInputStream(newFile);// 将excel文件转为输入流
  39. workbook = new XSSFWorkbook(is);// 创建个workbook,
  40. // 获取第一个sheet
  41. sheet = workbook.getSheetAt(0);
  42. } catch (Exception e1) {
  43. e1.printStackTrace();
  44. }
  45. if (sheet != null) {
  46. try {
  47. // 写数据
  48. FileOutputStream fos = new FileOutputStream(newFile);
  49. XSSFRow row = sheet.getRow(0);
  50. if (row == null) {
  51. row = sheet.createRow(0);
  52. }
  53. XSSFCell cell = row.getCell(0);
  54. if (cell == null) {
  55. cell = row.createCell(0);
  56. }
  57. cell.setCellValue("");
  58. // 合并单元格
  59. CellRangeAddress region = new CellRangeAddress(3,2+list.size(),1,1);
  60. sheet.addMergedRegion(region);
  61. String[] keyArry = keyStr.split(",");
  62. for (int i = 0; i < list.size(); i++) {
  63. PageData map = list.get(i);
  64. row = sheet.createRow(i+3); //从第四行开始
  65. cell = setCell(workbook,row,0);
  66. createRowAndCell(i+1, row, cell, 0);
  67. cell = setCell(workbook,row,1);
  68. if (i == 0) createRowAndCell(map.get("COMPANY"), row, cell, 1);
  69. else createRowAndCell("", row, cell, 1);
  70. for (int j = 0; j < keyArry.length; j++) {
  71. cell = setCell(workbook,row,j+2);
  72. createRowAndCell(map.get(keyArry[j]), row, cell, j+2);
  73. }
  74. }
  75. workbook.write(fos);
  76. fos.flush();
  77. fos.close();
  78. // 下载
  79. InputStream fis = new BufferedInputStream(new FileInputStream(newFile));
  80. byte[] buffer = new byte[fis.available()];
  81. fis.read(buffer);
  82. fis.close();
  83. response.reset();
  84. response.setContentType("text/html;charset=UTF-8");
  85. OutputStream toClient = new BufferedOutputStream(
  86. response.getOutputStream());
  87. response.setContentType("application/x-msdownload");
  88. String newName = URLEncoder.encode(fileName,"UTF-8");
  89. response.addHeader("Content-Disposition",
  90. "attachment;filename=\"" + newName + "\"");
  91. response.addHeader("Content-Length", "" + newFile.length());
  92. toClient.write(buffer);
  93. toClient.flush();
  94. } catch (Exception e) {
  95. e.printStackTrace();
  96. } finally {
  97. try {
  98. if (null != is) {
  99. is.close();
  100. }
  101. } catch (Exception e) {
  102. e.printStackTrace();
  103. }
  104. }
  105. }
  106. // 删除创建的新文件
  107. this.deleteFile(newFile);
  108. }
  109. /**
  110. *根据当前row行,来创建index标记的列数,并赋值数据
  111. */
  112. private void createRowAndCell(Object obj, XSSFRow row, XSSFCell cell, int index) {
  113. cell = row.getCell(index);
  114. if (cell == null) {
  115. cell = row.createCell(index);
  116. }
  117. if (obj != null)
  118. cell.setCellValue(obj.toString());
  119. else
  120. cell.setCellValue("");
  121. }
  122. /**
  123. * 复制文件
  124. * @param s
  125. * 源文件
  126. * @param t
  127. * 复制到的新文件
  128. */
  129. public void fileChannelCopy(File s, File t) {
  130. try {
  131. InputStream in = null;
  132. OutputStream out = null;
  133. try {
  134. in = new BufferedInputStream(new FileInputStream(s), 1024);
  135. out = new BufferedOutputStream(new FileOutputStream(t), 1024);
  136. byte[] buffer = new byte[1024];
  137. int len;
  138. while ((len = in.read(buffer)) != -1) {
  139. out.write(buffer, 0, len);
  140. }
  141. } finally {
  142. if (null != in) {
  143. in.close();
  144. }
  145. if (null != out) {
  146. out.close();
  147. }
  148. }
  149. } catch (Exception e) {
  150. e.printStackTrace();
  151. }
  152. }
  153. /**
  154. * 读取excel模板,并复制到新文件中供写入和下载
  155. *
  156. * @return
  157. */
  158. public File createNewFile(String tempPath, String rPath) {
  159. // 读取模板,并赋值到新文件
  160. // 文件模板路径
  161. String path = (tempPath);
  162. File file = new File(path);
  163. // 保存文件的路径
  164. String realPath = rPath;
  165. // 新的文件名
  166. String newFileName = System.currentTimeMillis() + ".xlsx";
  167. // 判断路径是否存在
  168. File dir = new File(realPath);
  169. if (!dir.exists()) {
  170. dir.mkdirs();
  171. }
  172. // 写入到新的excel
  173. File newFile = new File(realPath, newFileName);
  174. try {
  175. newFile.createNewFile();
  176. // 复制模板到新文件
  177. fileChannelCopy(file, newFile);
  178. } catch (Exception e) {
  179. e.printStackTrace();
  180. }
  181. return newFile;
  182. }
  183. /**
  184. * 下载成功后删除
  185. *
  186. * @param files
  187. */
  188. private void deleteFile(File... files) {
  189. for (File file : files) {
  190. if (file.exists()) {
  191. file.delete();
  192. }
  193. }
  194. }
  195. private XSSFCellStyle setStyle(XSSFWorkbook workbook) {
  196. XSSFCellStyle style = workbook.createCellStyle();
  197. style.setAlignment(HorizontalAlignment.CENTER);
  198. style.setBorderBottom(BorderStyle.THIN);
  199. style.setRightBorderColor(IndexedColors.BLACK.getIndex());
  200. style.setBorderLeft(BorderStyle.THIN);
  201. style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  202. style.setBorderTop(BorderStyle.THIN);
  203. style.setTopBorderColor(IndexedColors.BLACK.getIndex());
  204. style.setBorderBottom(BorderStyle.THIN);
  205. style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  206. style.setVerticalAlignment(VerticalAlignment.CENTER);
  207. return style;
  208. }
  209. private XSSFCell setCell(XSSFWorkbook workbook,XSSFRow row,int num){
  210. XSSFCell cell = row.createCell(num);
  211. XSSFCellStyle style = setStyle(workbook);
  212. cell.setCellStyle(style);
  213. return cell;
  214. }
  215. }