| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package com.template.common.utils;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.poi.ss.usermodel.Workbook;
- import org.springframework.boot.system.ApplicationHome;
- import javax.servlet.http.HttpServletResponse;
- import java.io.*;
- import java.net.URLDecoder;
- import java.net.URLEncoder;
- /**
- * @Author: binguo
- * @Date: 2023/7/10 星期一 14:21
- * @Description: com.repair.common.utils
- * @Version: 1.0
- */
- @Slf4j
- public class ExcelUtils {
- public static void fileDownload(String fileName, HttpServletResponse response) {
- try {
- ApplicationHome applicationHome = new ApplicationHome(ExcelUtils.class);
- String pathResouce = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
- String decode = URLDecoder.decode(pathResouce, "utf-8");
- File readPath = new File(decode + "/project/repair" + File.separator);
- File file = new File(readPath.getAbsolutePath() + fileName);
- // 获取文件名
- String filename = file.getName();
- // 获取文件后缀名
- String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
- InputStream inputStream = new FileInputStream(file);//根据路径获取要下载的文件输入流
- response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
- response.setCharacterEncoding("utf-8");
- response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
- OutputStream out = response.getOutputStream();
- byte[] b = new byte[1024]; //创建数据缓冲区
- int length;
- while ((length = inputStream.read(b)) > 0) { //把文件流写到缓冲区里
- out.write(b, 0, length);
- }
- out.flush();
- out.close();
- inputStream.close();
- } catch (IOException ex) {
- logger.info("模板导出失败:" + ex.getMessage());
- ex.printStackTrace();
- }
- }
- public static void excelDownload(Workbook workbook, String fileName, HttpServletResponse response) {
- try {
- response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
- response.setCharacterEncoding("utf-8");
- response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
- OutputStream out = response.getOutputStream();
- workbook.write(out);
- out.flush();
- out.close();
- } catch (IOException ex) {
- logger.info("模板导出失败:" + ex.getMessage());
- ex.printStackTrace();
- }
- }
- }
|