ExcelUtils.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.template.common.utils;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.poi.ss.usermodel.Workbook;
  4. import org.springframework.boot.system.ApplicationHome;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.*;
  7. import java.net.URLDecoder;
  8. import java.net.URLEncoder;
  9. /**
  10. * @Author: binguo
  11. * @Date: 2023/7/10 星期一 14:21
  12. * @Description: com.repair.common.utils
  13. * @Version: 1.0
  14. */
  15. @Slf4j
  16. public class ExcelUtils {
  17. public static void fileDownload(String fileName, HttpServletResponse response) {
  18. try {
  19. ApplicationHome applicationHome = new ApplicationHome(ExcelUtils.class);
  20. String pathResouce = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
  21. String decode = URLDecoder.decode(pathResouce, "utf-8");
  22. File readPath = new File(decode + "/project/repair" + File.separator);
  23. File file = new File(readPath.getAbsolutePath() + fileName);
  24. // 获取文件名
  25. String filename = file.getName();
  26. // 获取文件后缀名
  27. String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
  28. InputStream inputStream = new FileInputStream(file);//根据路径获取要下载的文件输入流
  29. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  30. response.setCharacterEncoding("utf-8");
  31. response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
  32. OutputStream out = response.getOutputStream();
  33. byte[] b = new byte[1024]; //创建数据缓冲区
  34. int length;
  35. while ((length = inputStream.read(b)) > 0) { //把文件流写到缓冲区里
  36. out.write(b, 0, length);
  37. }
  38. out.flush();
  39. out.close();
  40. inputStream.close();
  41. } catch (IOException ex) {
  42. logger.info("模板导出失败:" + ex.getMessage());
  43. ex.printStackTrace();
  44. }
  45. }
  46. public static void excelDownload(Workbook workbook, String fileName, HttpServletResponse response) {
  47. try {
  48. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  49. response.setCharacterEncoding("utf-8");
  50. response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
  51. OutputStream out = response.getOutputStream();
  52. workbook.write(out);
  53. out.flush();
  54. out.close();
  55. } catch (IOException ex) {
  56. logger.info("模板导出失败:" + ex.getMessage());
  57. ex.printStackTrace();
  58. }
  59. }
  60. }