vue.js前端实现excel表格导出和获取headers里的信息

前段时间写过一篇文章基于element实现后台管理系统,并提到excel表格导出功能,可能描述不是很详细,现在单独整理列出。

后端提供的接口:

// 下载分拣列表
export function getAssormentExport(params) {
  return request({
    url: '/manage/health/assorment/export?ids=' + params,
    responseType: 'arraybuffer', // 代表内存之中的一段二进制数据 必须加
    method: 'get'
  })
}

vue:点击按钮调用接口

<el-button type="primary" size="mini" @click="addexport()">导出选中</el-button>

script:

    // 导出选中
    addexport() {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          showClose: true,
          message: '未选中数据',
          type: 'error'
        })
        return
      }
      for (let i = 0; i < this.multipleSelection.length; i++) {
        this.ids.push(this.multipleSelection[i].id)
      } // push一个新的数组,存储需要导出信息的ID并传给接口实现数据返回
      getAssormentExport(this.ids).then(
        function(response) {
          const filename = decodeURI(response.headers['content-disposition'].split(';')[1].split('=')[1]) || '分拣表.xlsx'
          this.fileDownload(response.data, filename) // response.data是后端返回的二进制数据流,filename是获取到的导出文件名,获取失败使用默认值
          this.ids = []
        }.bind(this)
      ).catch(
        function(error) {
          this.$message({
            showClose: true,
            message: error,
            type: 'error'
          })
          this.ids = []
        }.bind(this)
      )
    },
    fileDownload(data, fileName) {
      const blob = new Blob([data], {
        type: 'application/octet-stream'
      })
      const filename = fileName || 'filename.xlsx'
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        var blobURL = window.URL.createObjectURL(blob)
        var tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    },

查看调用接口返回的信息

5cfd4731e2785b480a22306ec2d4f41acc0.jpg

备注:

1.response返回了包含响应头所带的所有数据,可以使用console.log(response)查看打印数据,但是打印出来的数据只能拿到默认的响应头,这里有个需要注意的地方。

  • Cache-Control

  • Content-Language

  • Content-Type

  • Expires

  • Last-Modified

  • Pragma

如果想让浏览器能访问到其他响应头的话,需要后端在服务器上设置Access-Control-Expose-Headers

Access-Control-Expose-Headers : 'content-disposition'

后端大致写法:

headers.add("Access-Control-Expose-Headers", "Content-Disposition");

这样response.headers['content-disposition'].split(';')[1].split('=')[1] 就能取到接口返回的文件名称了。

2. decodeURI的使用

decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。

实例

在本例中,我们将使用 decodeURI() 对一个编码后的 URI 进行解码:

<script type="text/javascript">

var test1="http://www.w3school.com.cn/My first/"

document.write(encodeURI(test1)+ "<br />")
document.write(decodeURI(test1))

</script>

输出:

http://www.w3school.com.cn/My%20first/
http://www.w3school.com.cn/My first/

 

转载于:https://my.oschina.net/lemonfive/blog/2052315

在Spring Boot中,可以使用Apache POI库来导出Excel文件并将其返回给前端进行下载。 首先,我们需要在pom.xml文件中添加Apache POI的依赖项: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 接下来,创建一个Excel导出的处理器方法。可以在Controller中创建一个方法,该方法使用`@RequestMapping`或`@GetMapping`注解来指定URL路径和HTTP请求方法。在该方法中,可以使用Apache POI来创建和填充Excel工作簿。例如,以下代码演示了如何在Excel中创建并填充一个简单的表格: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; @RequestMapping("/export") public ResponseEntity<Resource> exportExcel() throws IOException { // 创建Excel工作簿 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 填充数据 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("姓名"); headerRow.createCell(1).setCellValue("年龄"); Row dataRow = sheet.createRow(1); dataRow.createCell(0).setCellValue("张三"); dataRow.createCell(1).setCellValue(25); // 将工作簿转换为字节数组 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); byte[] excelBytes = outputStream.toByteArray(); // 创建HTTP响应体,并设置文件下载的相关头信息 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", "data.xlsx"); // 返回带有Excel文件的响应实体 return new ResponseEntity<>(new ByteArrayResource(excelBytes), headers, HttpStatus.OK); } ``` 在上面的代码中,我们创建了一个简单的Excel表格,并将其转换为字节数组形式。然后,我们创建了一个包含Excel文件的响应实体,并设置了HTTP响应头以指定文件下载的相关信息,例如文件名和Content-Type。最后,我们将响应实体返回给前端进行下载。 以上是一个简单的示例,你可以根据实际需求来创建更复杂的Excel导出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值