ExcelUtils.java 2.8 KB

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