springboot项目实现excel静态模板下载

excel静态模板下载,有两种方式:第一种,在http头中指定输出文件流的类型为"application/vnd.ms-excel"类型时,输出流时就不需要添加输出文件的后缀名;第二种,指定文件流的类型为"multipart/form-data"时,输出流时需要判断文件是.xls/.xlsx,并且加上后缀名。

1、方式一:(有些许问题需要改进)

controller层代码:

 @GetMapping("/download")   //此处尽量get请求,post不知为何有问题
    public Result<String> downLoadTemplate(HttpServletResponse response){   
    // 获取资源中的模板文件 
    ClassPathResource resource = new ClassPathResource("/templates/excel/涌金数据支付明细表模板.xls"); 
    InputStream inputStream = resource.getInputStream(); 
    // 根据excel创建对象 
    Workbook workbook = WorkbookFactory.create(inputStream);
    String fileName = "定义文件名";
    ExcelUtil.downLoadExcel(fileName, response, workbook);
    }
ExcelUtil工具类代码:
public class ExcelUtil {
  //模板下载工具类
  private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {    try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { // throw new NormalException(e.getMessage()); } } }

2、方式二:工具类可以提取整合

  @GetMapping("/download")   //此处尽量get请求,post不知为何有问题
    public Result<String> downLoadTemplate(HttpServletResponse response) {
        try {
            // 获取资源中的模板文件
            ClassPathResource resource = new ClassPathResource("/templates/excel/涌金数据支付明细表模板.xls");
            InputStream inputStream = resource.getInputStream();
            // 根据不同excel创建不同对象,Excel2003版本-->HSSFWorkbook,Excel2007版本-->XSSFWorkbook
            Workbook wb = WorkbookFactory.create(inputStream);        
            response.reset();
            response.setContentType("multipart/form-data");
            // 判断excel文件类型,下载获取到的模板并重新命名
            System.out.println(wb.getClass().getSimpleName());
            if (wb.getClass().getSimpleName().equals("HSSFWorkbook")) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String("定义文件名称".getBytes("UTF-8"), "iso8859-1") + ".xls");
            } else {
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String("定义文件名称".getBytes("UTF-8"), "iso8859-1") + ".xlsx");
            }
            wb.write(response.getOutputStream());
  }

注意:无论是方式一还是方式二,都是静态模板导出,都需要将模板放在模板资源文件夹下,如下图:

 

转载于:https://www.cnblogs.com/H-Dream/p/11408368.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值