下载工程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);
        }
    }
相关推荐
SabreWulf20203 小时前
Excel打开灰色空白无内容
excel
それども12 小时前
Apache POI XSSFWorkbook 和 SXSSFWorkbook 的区别
apache·excel
—Miss. Z—18 小时前
Power Query数据分类整合
excel
开开心心就好1 天前
系统管理工具,多功能隐私清理文件粉碎工具
java·网络·windows·r语言·电脑·excel·symfony
sinat_375112261 天前
abap excel上传
excel·上传·sap·abap
·云扬·1 天前
【实操教程】Excel文件转CSV并导入MySQL的完整步骤
android·mysql·excel
城数派1 天前
2019-2025年各区县逐月新房房价数据(Excel/Shp格式)
大数据·数据分析·excel
Elieal1 天前
EasyExcel 实现 Excel 导入导出
java·excel
徐赛俊2 天前
Excel 打开后界面一片灰、无工作表的原因与解决方案(Markdown 教程)
excel
hacker7072 天前
精进Excel图表:AI赋能,成为Excel图表高手
人工智能·信息可视化·excel