1. package com.business.testExcelPort;
    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.IOException;
    8. import java.io.InputStream;
    9. import java.io.OutputStream;
    10. import java.net.URLEncoder;
    11. import java.util.ArrayList;
    12. import java.util.Calendar;
    13. import java.util.List;
    14. import java.util.Random;
    15. import javax.servlet.http.HttpServletResponse;
    16. import com.alibaba.excel.EasyExcel;
    17. import com.alibaba.excel.read.listener.ReadListener;
    18. import com.alibaba.excel.support.ExcelTypeEnum;
    19. import org.apache.log4j.Logger;
    20. import org.apache.tools.zip.ZipEntry;
    21. import org.apache.tools.zip.ZipOutputStream;
    22. import org.springframework.stereotype.Controller;
    23. import org.springframework.web.bind.annotation.RequestMapping;
    24. import org.springframework.web.bind.annotation.RequestMethod;
    25. /**
    26. * @ClassName DownLoad
    27. * @Deacription TODO
    28. * @Author SEN
    29. * @Date 2020/2/10 0010 17:49
    30. * @Version 1.0
    31. **/
    32. @Controller
    33. @RequestMapping("/download")
    34. @Slf4j
    35. public class DownLoad {
    36. private Logger Log = Logger.getLogger(DownLoad.class);
    37. // 获取当前系统的临时目录
    38. private static final String FilePath = System.getProperty("java.io.tmpdir") + File.separator;
    39. @RequestMapping(value = "/execute", method=RequestMethod.GET)
    40. public void execute(HttpServletResponse response) {
    41. // 用于存放文件路径
    42. List<String> filePaths = new ArrayList<>();
    43. //生成的ZIP文件名为Demo.zip
    44. String tmpFileName = "Demo.zip";
    45. // zip文件路径
    46. String strZipPath = FilePath + tmpFileName;
    47. filePaths.add(strZipPath);
    48. try {
    49. //创建zip输出流
    50. ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
    51. //声明文件集合用于存放excel文件
    52. List<File> fileList = new ArrayList<File>();
    53. //生成excel文件集合
    54. for (int i = 0; i < 10; i++) {
    55. // 生成随机文件名
    56. String filename = FilePath + generateRandomFilename() + ".xlsx";
    57. // 将文件路径保存
    58. fileList.add(creatFile(filename));
    59. filePaths.add(filename);
    60. List<DataOne> list = new ArrayList<>();
    61. for (int j = 0; j < 10; j++) {
    62. // 造一些表格数据,一般是从数据库查出来的list集合数据
    63. DataOne dataOne = new DataOne();
    64. //。。。
    65. list.add(dataOne);
    66. }
    67. // 使用easyexcel生成excel文件
    68. writeExcel(newFile, DataOne.class, list,ExcelTypeEnum.XLS);
    69. }
    70. byte[] buffer = new byte[1024];
    71. //将excel文件放入zip压缩包
    72. for (int i = 0; i < fileList.size(); i++) {
    73. File file = fileList.get(i);
    74. FileInputStream fis = new FileInputStream(file);
    75. out.putNextEntry(new ZipEntry(file.getName()));
    76. //设置压缩文件内的字符编码,不然会变成乱码
    77. out.setEncoding("GBK");
    78. int len;
    79. // 读入需要下载的文件的内容,打包到zip文件
    80. while ((len = fis.read(buffer)) > 0) {
    81. out.write(buffer, 0, len);
    82. }
    83. out.closeEntry();
    84. fis.close();
    85. }
    86. out.close();
    87. //下载zip文件
    88. this.downFile(response, tmpFileName,filePaths);
    89. } catch (Exception e) {
    90. // 下载失败删除生成的文件
    91. deleteFile(filePaths);
    92. Log.error("文件下载出错", e);
    93. }
    94. }
    95. /**
    96. * 文件下载
    97. * @param response
    98. * @param str
    99. * @param filePaths
    100. */
    101. private void downFile(HttpServletResponse response, String str, List<String> filePaths) {
    102. try {
    103. String path = FilePath + str;
    104. File file = new File(path);
    105. if (file.exists()) {
    106. InputStream ins = new FileInputStream(path);
    107. BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
    108. OutputStream outs = response.getOutputStream();// 获取文件输出IO流
    109. BufferedOutputStream bouts = new BufferedOutputStream(outs);
    110. response.setContentType("application/x-download");// 设置response内容的类型
    111. response.setHeader(
    112. "Content-disposition",
    113. "attachment;filename="
    114. + URLEncoder.encode(str, "UTF-8"));// 设置头部信息
    115. int bytesRead = 0;
    116. byte[] buffer = new byte[8192];
    117. // 开始向网络传输文件流
    118. while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
    119. bouts.write(buffer, 0, bytesRead);
    120. }
    121. bouts.flush();// 这里一定要调用flush()方法
    122. ins.close();
    123. bins.close();
    124. outs.close();
    125. bouts.close();
    126. deleteFile(filePaths);
    127. }
    128. } catch (IOException e) {
    129. deleteFile(filePaths);
    130. Log.error("文件下载出错", e);
    131. }
    132. }
    133. //创建文件File对象
    134. private File creatFile(String filePath) {
    135. File file = new File(filePath);
    136. return file;
    137. }
    138. //生成随机文件名
    139. public String generateRandomFilename() {
    140. String RandomFilename = "";
    141. Random rand = new Random();//生成随机数
    142. int random = rand.nextInt();
    143. Calendar calCurrent = Calendar.getInstance();
    144. int intDay = calCurrent.get(Calendar.DATE);
    145. int intMonth = calCurrent.get(Calendar.MONTH) + 1;
    146. int intYear = calCurrent.get(Calendar.YEAR);
    147. String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
    148. String.valueOf(intDay) + "_";
    149. RandomFilename = now + String.valueOf(random > 0 ? random : (-1) * random);
    150. return RandomFilename;
    151. }
    152. //删除文件
    153. public static boolean deleteFile(List<String> filePath){
    154. boolean result = false;
    155. for (String pathname:filePath){
    156. File file = new File(pathname);
    157. if (file.exists()) {
    158. file.delete();
    159. result = true;
    160. }
    161. }
    162. return result;
    163. }
    164. /**
    165. * @Title: writeExcel
    166. * @Description: 写入excel文件到输出流web端
    167. *
    168. */
    169. private void writeExcel(OutputStream outputStream, Class<?> clazz, List<?> datalist,ExcelTypeEnum excelType,String sheetName) throws IOException {
    170. EasyExcel.write(outputStream, clazz).excelType(excelType).sheet(sheetName==null ? "sheet1":sheetName).doWrite(datalist);
    171. outputStream.flush();
    172. }
    173. /**
    174. * @Title: writeExcel
    175. * @Description: 写入excel到本地路径
    176. */
    177. private void writeExcel(File newFile, Class<?> clazz, List<?> datalist,ExcelTypeEnum excelType) {
    178. EasyExcel.write(newFile, clazz).excelType(excelType).sheet("sheet1").doWrite(datalist);
    179. }
    180. /**
    181. * @Title: readExcel
    182. * @Description: 读取excel内容(从输入流)
    183. */
    184. private List<?> readExcel(InputStream inputStream, Class<?> clazz, ReadListener<?> listener) {
    185. List<?> list = null;
    186. list = EasyExcel.read(inputStream, clazz, listener).sheet().doReadSync();
    187. return list;
    188. };
    189. }