Download a CSV file using JavaScript

Source: Internet
Author: User

The front end can use JavaScript to download the file containing the page data in the client, here is the CSV format file as an example, the code is as follows:

function downloadData(data, filename, type) {    var file = new Blob(["\ufeff" + data], { type: type });    if (window.navigator.msSaveOrOpenBlob)      // IE10+      window.navigator.msSaveOrOpenBlob(file, filename);    else {      // Others      var a = document.createElement("a"),        url = URL.createObjectURL(file);      a.href = url;      a.download = filename;      document.body.appendChild(a);      a.click();      setTimeout(function() {        document.body.removeChild(a);        window.URL.revokeObjectURL(url);      }, 0);    }  }

Let's explain this code:

(i) Downloaddata function

First, the downloadData function receives three parameters:

    1. data: Data to be downloaded (note that the data format needs to conform to the CSV format specification);
    2. filename: Need to download the file name, note the need to add a file name in accordance with the data format suffix, which indicates how the operating system should open;
    3. type: Represents the Blob MIME type of the array content that will be put into the object;
(ii) Blob constructor

Next, let's parse the following statement:

var file = new Blob(["\ufeff" + data], { type: type });

As you can see, we used the Blob constructor to create a blob instance object file . BlobWhat is the use of constructors? What are the two parameters it receives? Let us answer the following:

The function of ①blob constructor

The Blob constructor constructs a new instance of the Blob object based on the array parameters passed in, and the value of the object instance is generated by the following two steps:

    1. The Blob constructor concatenates the first parameter, which is all the values in an array;
    2. The blob converts the concatenated value into binary encoded data and returns it;

Note that the value of the Blob object instance is immutable, and it has only two read-only properties: size the size of the data contained in the object (in bytes), and type : The value is a string, Represents the MIME type of the data that the object instance contains (that is, the value specified in the second parameter of our incoming BLOB constructor type , by default "" ).

②blob parameters received by the constructor function

The first parameter received by the Blob constructor is an array type, and all values in the arrays are concatenated when instantiated. If the value of the incoming array has a DOMString value of type, it is encoded in the UTF-8 format. In order for the exported CSV format file to open in Excel, Chinese does not appear garbled, you need to add a BOM (byte order mark) header in the first place of the array \ufeff .

BOM is an invisible character, it is ES5 new white space character, before Unicode3.2, \uFEFF said "0 wide non-line space (Zero width no-break space)", but after Unicode3.2, a new \u2060 Represents a 0-wide non-newline space, which \uFEFF is used only to represent the token of the byte order. In Microsoft, its Notepad program invented a UTF-8 variant (Python 2.5 called "Utf-8-sig") to improve the reliability of UTF-8 encoding that can be detected. The code requires writing a UTF-8-encoded BOM (which looks like a sequence of bytes: 0XEF,0XBB,0XBF) before any Unicode characters are written.

The second parameter that is received by the Blob constructor is an object that has the following two properties:

    1. type: The default value is a "" MIME type that represents the contents of the array within the first parameter;
    2. options: This attribute is not well supported at this time, so do not care about it;

In short, we new Blob() obtained a binary file of blob type.

(iii) Download file

Then all we have to do is download our generated files, there are two ways, the first way is the simplest, because IE browser directly provides the interface to download the file, window.navigator.msSaveOrOpenBlob(file, filename); as the function signature shows, we only need to pass to the function of our generated binary file, And the file name will allow the browser to download files automatically.

To get rid of IE browser, to achieve file download is a little more trouble, we need to create a tag, and simulate click on the A-tag implementation of the file download, let us paste the relevant code below:

var a = document.createElement("a"),     url = URL.createObjectURL(file);a.href = url;a.download = filename;document.body.appendChild(a);a.click();setTimeout(function() {  document.body.removeChild(a);  window.URL.revokeObjectURL(url);}, 0);

Note that the second line of the code, we will find a new API: URL.createObjectURL() function, this function takes a parameter, a BLOB object, and generates a URL object for the object, it is important to note that as long as the current document is not closed, The URL object will always be stored in memory and will not be recycled, so once you determine that the URL object is no longer needed, be sure to use cleanup in a timely manner URL.revokeObjectURL() .

Above, we explained the method and principle of downloading data in CSV format at the front end, it should be noted that this code only applies to the modern browsers of IE10 and above, because both the Blob constructor and the URL.createObjectURL() API are only supported by these browsers.

Download a CSV file using JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.