springboot+vue+element-ui下载excel模板(静态文件)

前端: 

html:
      <div style="margin-top: 20px">
        <el-button  @click="downloadDemo" size="small">下载模板</el-button>
      </div>

js:


      downloadDemo () {
        let url = Config.context + '/userManager/downloadExcel'
        this.common.exportData(url, this.queryForm, '数据模板_' + this.common.getTime())
      }
  exportData (url, data, fileName) {
    axios({
      method: 'POST',
      url: url,
      data: data,
      responseType: 'blob'
    }).then(response => {
      if (!response) {
        return
      }
      const blob = new Blob([response.data])
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName)
      } else {
        let u = window.URL.createObjectURL(response.data)
        let aLink = document.createElement('a')
        aLink.style.display = 'none'
        aLink.href = u
        aLink.setAttribute('download', fileName + '.xlsx')
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink)
        window.URL.revokeObjectURL(u)
      }
    }).catch(error => {
      throw error
    })
  }

 

后端:

controller层:

    @RequestMapping("/downloadExcel")
    public ResponseEntity<byte[]> download2() throws IOException {
        File file = excelModelService.buildXlsById();
        return FileUtils.buildResponseEntity(file);
    }

service层:

import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;

@Service
public class ExcelModelService {
    public File buildXlsById(){
        //do something to find this file
        File file=null;
        try {
            file = ResourceUtils.getFile("classpath:templates/model.xlsx");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file;
    }
}

这里写的是静态文件的存放路径,注意不能中文名不然识别不了

文件下载工具类:

    public static ResponseEntity<byte[]> buildResponseEntity(File file) throws IOException {
        byte[] body = null;
        //获取文件
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        //设置文件类型
        headers.add("Content-Disposition", "attchement;filename=" + file.getName());
        //设置Http状态码
        HttpStatus statusCode = HttpStatus.OK;
        //返回数据
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }

后续补充:

  以上方式实现在开发环境没有任何问题,但是在生产环境会出现无法下载后台报错的情况,原因在于用流的方式读取文件,打成jar包之后,下载的文件会被损坏 ,后来网上说配置pom里面文件路径等等试了没用,直接用了POI的导出

修改后controller:

   @RequestMapping(value="/downloadExcel")
    public ResponseEntity<Resource> excel2007Export(HttpServletResponse response, HttpServletRequest request) {
        try {
            ClassPathResource cpr = new ClassPathResource("/templates/"+"model.xlsx");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            String fileName = "model.xlsx";
            downLoadExcel(fileName, response, workbook);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new ResponseEntity<Resource>(HttpStatus.OK);
    }

文件工具类downLoadExcel:

    public 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) {
            e.printStackTrace();
        }
    }

 

  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值