第十七篇 - 下载XLSX文件的两种方式

发布时间 2023-09-27 10:53:16作者: o云淡风轻o

这篇介绍Excel下载的两种方式。SpringMVC + Vue3

一、使用BLOB文件流下载Excel

参考链接:https://blog.csdn.net/m0_66607230/article/details/129161820

先来看看后端Controller的代码

controller.java

@RequestMapping(value = "/downloadExcel", method = RequestMethod.POST)
    @ResponseBody
    public void DownloadExcel(@ModelAttribute("User") User user, HttpServletRequest request, HttpServletResponse response) throws IOException{
//        String excel_path = request.getParameter("test_excel_path"); // 前端传递模板excel路径
        String excel_path = "D:\\test.xlsx"; // 直接定义模板excel路径进行测试
        Workbook wb = null;
        Sheet sheet = null;
        FileInputStream inputStream = new FileInputStream(excel_path);
        wb = new XSSFWorkbook(inputStream); // 读取模板表格内容
        if (wb != null) {
            try {
                sheet = wb.getSheetAt(18); // 读取第18个sheet,excel表中sheet是从0开始数起
                Row row = sheet.getRow(2);  // 定位excel的第2行,行数也是从0开始数起
                Cell cell1 = row.getCell(2); // 定位excel的第2行第2列,列数也是从0数起
                System.err.println(getStringCellValue(cell1)); // 打印第2行第2列的字符串
                Cell word = row.getCell(3);  // 定位excel的第2行第3列
                word.setCellValue("test words"); // 设置excel的第2行第3列的信息为test words

                response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 设置响应格式,前端要与这保持一致
                response.setHeader("Content-Disposition",
                        "attachment;filename=\"" + new String(("文档名称.xlsx").getBytes("gb2312"), "ISO8859-1"));
                OutputStream output = response.getOutputStream();
                wb.write(output); // 将修改后的表格信息写入response输出
                output.close();
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
View Code

 

这一段代码就是返回的blob文件流。

再来看看前端Vue如何接收

async downloadExcel() {
      let data_excel = {
        "test_excel_path": this.testexcelpath,
      }
      // 后端保存excel
      await axios
          .post('http://ip:port/project/downloadExcel', qs.stringify(data_excel), {responseType: 'blob'})
          .then(successResponse => {
            console.log(successResponse.data)
            var a = document.createElement('a')
            const blob = new Blob([successResponse.data],{type: 'application/vnd.ms-excel'})
            a.href = URL.createObjectURL(blob)
            a.download = "aaa.xlsx"
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            console.log("下載成功")
          })
          .catch(failResponse => {
            console.log(failResponse)
          })
}
View Code

 

这样点击下载按钮时,会触发downloadExcel函数,浏览器会把它下载到客户端默认的下载文件夹中

 

二、服务器存在excel本地文件,客户端通过windows.open访问URL下载