[测评系统]--测评系统核心代码库
林致杰
2022-06-26 99f7f9adac08f3a3fa3211f7a6062c26d62fa224
src/main/java/com/ots/framework/web/controller/BaseController.java
@@ -1,4 +1,5 @@
package com.ots.framework.web.controller;
import cn.hutool.core.util.URLUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ots.common.utils.DateUtils;
@@ -11,9 +12,19 @@
import com.ots.framework.web.page.TableDataInfo;
import com.ots.framework.web.page.TableSupport;
import com.ots.project.system.user.domain.User;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
@@ -112,4 +123,39 @@
        }
        return json;
    }
    public void downDeviceManagementTemplate(String fileName, String path , HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
        // 读取服务器端模板文件
        // ClassPathResource类的构造方法接收路径名称,自动去classpath路径下找文件
        ClassPathResource classPathResource = new ClassPathResource(path);
        //创建临时文件
        XSSFWorkbook workbook = null;
        try (InputStream inputStream = classPathResource.getInputStream()) {
            // 转为POI的Workbook输出流,这样下载后 打开不报错,直接输出  流 的话,打开excel可能提示错误
            workbook = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("模板下载异常");
        }
        String userAgent = req.getHeader("User-Agent");
        // 针对IE或者以IE为内核的浏览器:
        if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {
            fileName = URLUtil.encode(fileName, Charset.forName("UTF-8"));
        } else {
            // 非IE浏览器的处理:
            fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        }
        res.setHeader("Content-disposition", "attachment; filename=" + fileName);
        res.setContentType("application/vnd.ms-excel; charset=utf-8");
        res.setCharacterEncoding("UTF-8");
        // 将流中内容写出去
        try (OutputStream outputStream = res.getOutputStream()) {
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("模板下载异常");
        }
    }
}