最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Downloading a CSV of file using Vue and JS - Stack Overflow

programmeradmin1浏览0评论

I have a field called csvdata that contains an array of the following format:

[
    [1,2,3],
    [4,5,6],
    [7,8,9]
]

I'm trying to download a CSV file of this data. I'm using Vue so it looks like:

<button type="button" class="btn btn-info action_btn" v-on:click="downloadCSVData">
      Download
</button>

How should the downloadCSVData function look like?

I have a field called csvdata that contains an array of the following format:

[
    [1,2,3],
    [4,5,6],
    [7,8,9]
]

I'm trying to download a CSV file of this data. I'm using Vue so it looks like:

<button type="button" class="btn btn-info action_btn" v-on:click="downloadCSVData">
      Download
</button>

How should the downloadCSVData function look like?

Share Improve this question asked Oct 8, 2019 at 19:19 vesiivesii 3,1288 gold badges36 silver badges93 bronze badges 1
  • you need a backend scripting language such as PHP to process that array into a downloadable file. – Oliver M Grech Commented Oct 8, 2019 at 19:26
Add a comment  | 

3 Answers 3

Reset to default 28

I think you can create a method like so, assuming csvdata is a data property accessible by this in your Vue component:

downloadCSVData() => {
    let csv = 'Put,Column,Titles,Here\n';
    this.csvdata.forEach((row) => {
            csv += row.join(',');
            csv += "\n";
    });
 
    const anchor = document.createElement('a');
    anchor.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    anchor.target = '_blank';
    anchor.download = 'nameYourFileHere.csv';
    anchor.click();
}

Here is the working code to download a csv file in vue

This sample code converts array of objects to perfect csv file with headers call the function exportCSVFile(headers, items, fileTitle)

headers = { name: 'Name' // formatted column name, age: 'Age' }

items = [ { name: 'Joo', age: 21 }, { name: 'ant', age: 20 } ]

filename = 'somefilename.csv'

function convertToCSV(objArray) {
  const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
  let str = '';
  for (let i = 0; i < array.length; i++) { // eslint-disable-line
    let line = '';
    for (const index in array[i]) { // eslint-disable-line
      if (line !== '') line += ',';
      line += array[i][index];
    }
    str += line + '\r\n'; // eslint-disable-line
  }
  return str;
}

function exportCSVFile(headers, items, fileTitle) {
  if (headers) {
    items.unshift(headers);
  }
  const jsonObject = JSON.stringify(items);
  const csv = convertToCSV(jsonObject);
  const exportedFilenmae = fileTitle + '.csv' || 'export.csv'; // eslint-disable-line
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  if (navigator.msSaveBlob) { // IE 10+
    navigator.msSaveBlob(blob, exportedFilenmae);
  } else {
    const link = document.createElement('a');
    if (link.download !== undefined) {
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', exportedFilenmae);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
}

export default exportCSVFile;

If the given value is 2d array, just use this function

function downloadCSVData () {
    var array = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
    ];
    var str = '';
    for (var i = 0; i < array.length; i++) { 
    let line = '';
    line = array[i].join(",");
    str += line + '\r\n';
    }
    var blob = new Blob([str], { type: 'text/csv;charset=utf-8;' });

    var link = document.createElement('a');
    var url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'csvfilename.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
  1. Convert the Array to text. (let data = [[1,2,3], [4,5,6], [7,8,9]].join('\r\n').toString())
  2. Convert the text to base64. (let encoded_data = btoa(data))
  3. Create an iFrame and set its src = the encoded data. let iframe = document.createElement('iframe'); iframe.src = "data:application/octet-stream;base64," + encoded_data
  4. Append the iframe to the document's body: document.body.appendChild(iframe).

There's some drawbacks to this approach though:

  1. Content Security Policy can block step 4. You have control over CSP in your page, but don't sacrifice security for easy code.
  2. The file will always be named "download" with no file extension.

A better approach would be to create a temporary file on the server and provide the user a link to that file.

发布评论

评论列表(0)

  1. 暂无评论