The front end realizes the export and download of excel files (Blob data type)

Scenes

In various front-end background management systems, there are often a large amount of data display, analysis, etc. Generally, this kind of project will have a data export function. In development, the back-end usually returns the Blob data type, which is a binary object. , then this article is to explain how to deal with the Blob data obtained by the front end.

1. Blob

Here we briefly talk about Blob, the full name of Binary large Object, binary large object (BLOB) is a data type that can store binary objects or data.

The constructor syntax of the Blob object in the front end:

new Blob(array, options)

The parameter array is a data sequence, that is, an array, which can be a value in any format, for example, any number of strings, Blobs, and ArrayBuffers.
Parameter options: used to specify the type of data to be put into the blob (MIME)

2. Code

1. Remember to add responseType when encapsulating the request.

   /**
     * 导出exportExcel
     * @param data
     */
    public static exportExcel(data) {
        return axios({
            url: ``,
            method: 'get',
            params: data,
            responseType: "blob"//定义好返回的数据类型
        });
    }

Just follow your own packaged request here, just add responseType: "blob".

2. Get the Blob data type and convert it into a file and download it.

/**
 * 导出文件下载方法
 * @param data 这个参数就是从接口返回的Blob二进制文件流
 */
const exportFile= (data) => {
      const blob = new Blob([data], {type: "application/vnd.ms-excel;charset=utf-8"});
      const fileName = "文件名" + new Date().getTime() + ".xls";//我这里是文件名加上时间,可以根据自己需求来
      const elink = document.createElement("a"); // 创建a标签
      elink.download = fileName; // 为a标签添加download属性  //命名下载名称
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click(); // 点击下载
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink); // 释放标签
}

The words here can be encapsulated as a public method according to your own needs, and the file name is also set as an input parameter. The method of exporting and downloading the binary file stream as an excel table is generally like this.

Guess you like

Origin blog.csdn.net/G_ing/article/details/128170853