下载工程resources目录下的模板excel文件

一、添加依赖

复制代码
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.1.0</version>
</dependency>

二、编写接口

复制代码
@GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletRequest request,
                                 HttpServletResponse response){
        String fileName = "template"+File.separator+"字段标准导入模板.xlsx";
        InputStream is = ClassLoader.getSystemResourceAsStream(fileName);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        Workbook wb = null;
        try {
            wb = new XSSFWorkbook(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("下载导入模板异常{}", e.getMessage());
        } finally {
            IOUtils.closeQuietly(wb);
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

三、这种代码,在windows上调试没问题,打成jar包发到linux环境上会有问题,改成如下代码就行:

复制代码
@GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletRequest request,
                                 HttpServletResponse response){
        String fileName = "template"+File.separator+"ColumnStandardImportTemplate.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try (InputStream is = new ClassPathResource(fileName).getInputStream();
             Workbook wb = new XSSFWorkbook(is);
             ServletOutputStream os = response.getOutputStream()) {
            wb.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("下载导入模板异常", e);
        }
    }
相关推荐
盛夏绽放8 小时前
Vue3 中 Excel 导出的性能优化与实战指南
vue.js·excel
Tomorrow'sThinker11 小时前
[特殊字符] Python 自动查找替换 Excel 单元格内容 —— 高效批量处理
excel
Shipley Leo11 小时前
如何在Excel中每隔几行取一行
excel
bing_15811 小时前
Excel 数据透视表不够用时,如何处理来自多个数据源的数据?
excel
想要入门的程序猿14 小时前
Qt写入excel
数据库·qt·excel
爱代码的小黄人1 天前
Excel VLOOKUP函数使用详解:原理、格式、常见错误与解决方案
excel
YouYOUyouFairy1 天前
EXCEL动态表格
excel
Maruko3101 天前
Java 实现excel大批量导出
excel·poi
忧郁的蛋~1 天前
HTML表格导出为Excel文件的实现方案
前端·html·excel
不坑老师2 天前
利用不坑盒子的Copilot,快速排值班表
microsoft·word·powerpoint·excel·copilot·wps