Java:excel模板下载


前言

需求:项目中需要excel的导入功能,就需要相关excel的模板配置,将配置好的模板上传服务器,直接下载后插入数据上传解析等。


提示:以下是本篇文章正文内容,下面案例可供参考

一、出现的问题

  1. 本地测试通过,文件上传linux服务器,下载无返回值或返回值为空,导致下载的excel为0kb,无内容。
  2. 解决方法

1.使用 ClassPathResource resource = new ClassPathResource(filePath); 读取文件
2.使用 XSSFWorkbook wb = new XSSFWorkbook(fileInputStream); 转流

二、具体的代码

  • 模板文件放置的路径:resources/template/excel
    在这里插入图片描述
  • 代码详情
package com.sty.resource.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@Api(tags = "excel模板下载")
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * excel模板下载
     * @param response res
     * @param fileName 文件名全称,例:分组模板.xlsx
     */
    @ApiOperation("excel模板下载")
    @GetMapping("/template/download/{fileName}")
    public void downloadExcel(HttpServletResponse response, @PathVariable("fileName") String fileName) {
        log.info("excel文件模板名称:" + fileName);
        try (
            InputStream fileInputStream = (new ClassPathResource("template/excel/" + fileName)).getInputStream();
            XSSFWorkbook wb = new XSSFWorkbook(fileInputStream);
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())
        ) {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            wb.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("文件模板下载异常: {}", e.getMessage(), e);
        }
    }
}

总结

中心藏之,何日忘之。你是否体会的到?

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值