📜  如何在 JavaScript 中创建和下载 CSV 文件?

📅  最后修改于: 2022-05-13 01:56:14.157000             🧑  作者: Mango

如何在 JavaScript 中创建和下载 CSV 文件?

有时我们需要以 CSV 文件的形式获取数据,它可能是用户的详细信息或其他用于机器学习或分析目的的数据。我们可以轻松地从任何 javascript 对象或 JSON 文件中获取数据并以 CSV 文件的形式下载。

在本文中,我们将处理 2 个数据源:

  1. Javascript 对象
  2. JSON 对象

数据源:Javascript 对象

方法:简而言之,我们需要由 javascript 对象键引用的标头,以及由 javascript 对象值引用的行。我们需要将它们用逗号分隔以使其成为 CSV。我们使用 Blob 来构建 CSV 文件。

// Javascript Object
const data = {
    id: 1,
    name: "Geeks",
    profession: "developer"
}

这应该转换为:

id, Geeks, profession
1, Geeks, developer

第 1 步:设置项目

索引.html

<
main.js

第 2 步:在 main.js 中创建一个 csvmaker函数。该函数负责以 CSV 的形式制作普通的Java对象。
main.js

输出:

第三步:创建下载函数。此函数将使我们能够下载包含我们传递的数据的 CSV 文件。

Javascript
const download = function (data) {
 
    // Creating a Blob for having a csv file format
    // and passing the data with type
    const blob = new Blob([data], { type: 'text/csv' });
 
    // Creating an object for downloading url
    const url = window.URL.createObjectURL(blob)
 
    // Creating an anchor(a) tag of HTML
    const a = document.createElement('a')
 
    // Passing the blob downloading url
    a.setAttribute('href', url)
 
    // Setting the anchor tag attribute for downloading
    // and passing the download file name
    a.setAttribute('download', 'download.csv');
 
    // Performing a download with click
    a.click()
}
 
const csvmaker = function (data) {
 
    // Empty array for storing the values
    csvRows = [];
 
    // Headers is basically a keys of an
    // object which is id, name, and
    // profession
    const headers = Object.keys(data);
 
    // As for making csv format, headers
    // must be separated by comma and
    // pushing it into array
    csvRows.push(headers.join(','));
 
    // Pushing Object values into array
    // with comma separation
    const values = Object.values(data).join(',');
    csvRows.push(values)
 
    // Returning the array joining with new line
    return csvRows.join('\n')
}
 
const get = async function () {
 
    // JavaScript object
    const data = {
        id: 1,
        name: "Geeks",
        profession: "developer"
    }
 
    const csvdata = csvmaker(data);
    download(csvdata);
}
 
// Getting element by id and adding
// eventlistner to listen everytime
// button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);


Javascript
const get = async function () {
 
    // Json Get url
    const url = 'https://data.covid19india.org/data.json';
 
    // Fetching a data in a form of json objects
    const res = await fetch(url);
    const jsonobj = await res.json();
 
    // Getting statewise data (according to json objects)
    const jsondata = jsonobj.statewise
 
    // Making an object and mapping though the data
    // with keys and values
    const data = jsondata.map(row => ({
        state: row.state,
        statecode: row.statecode,
        active: row.active,
        confirmed: row.confirmed,
        deaths: row.deaths
    }))
 
    // console.log(jsondata)
 
    // console.log(csvmaker(data))
 
    const csvdata = csvmaker(data);
    download(csvdata);
 
}


Javascript
const download = function (data) {
 
    // Creating a Blob for having a csv file format
    // and passing the data with type
    const blob = new Blob([data], { type: 'text/csv' });
 
    // Creating an object for downloading url
    const url = window.URL.createObjectURL(blob)
 
    // Creating an anchor(a) tag of HTML
    const a = document.createElement('a')
 
    // Passing the blob downloading url
    a.setAttribute('href', url)
 
    // Setting the anchor tag attribute for downloading
    // and passing the download file name
    a.setAttribute('download', 'download.csv');
 
    // Performing a download with click
    a.click()
}
 
const csvmaker = function (data) {
 
    // Empty array for storing the values
    csvRows = [];
 
    // Headers is basically a keys of an
    // object which is id, name, and
    // profession
    const headers = Object.keys(data);
 
    // As for making csv format, headers
    // must be separated by comma and
    // pushing it into array
    csvRows.push(headers.join(','));
 
    // Pushing Object values into array
    // with comma separation
    const values = Object.values(data).join(',');
    csvRows.push(values)
 
    // Returning the array joining with new line
    return csvRows.join('\n')
}
 
const get = async function () {
 
    // JavaScript object
    const data = {
        id: 1,
        name: "Geeks",
        profession: "developer"
    }
 
    const csvdata = csvmaker(data);
    download(csvdata);
}
 
// Getting element by id and adding
// eventlistner to listen everytime
// button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);


输出:

数据源:JSON 对象

JSON对象的过程类似

  • 我们需要通过 JSON 文件进行 javascript 对象映射。它将与我们之前使用的数据一样工作。

Javascript

const get = async function () {
 
    // Json Get url
    const url = 'https://data.covid19india.org/data.json';
 
    // Fetching a data in a form of json objects
    const res = await fetch(url);
    const jsonobj = await res.json();
 
    // Getting statewise data (according to json objects)
    const jsondata = jsonobj.statewise
 
    // Making an object and mapping though the data
    // with keys and values
    const data = jsondata.map(row => ({
        state: row.state,
        statecode: row.statecode,
        active: row.active,
        confirmed: row.confirmed,
        deaths: row.deaths
    }))
 
    // console.log(jsondata)
 
    // console.log(csvmaker(data))
 
    const csvdata = csvmaker(data);
    download(csvdata);
 
}


  • 我们需要遍历对象值并将它们推送到main.js 中 csvmaker函数中的数组

Javascript

const download = function (data) {
 
    // Creating a Blob for having a csv file format
    // and passing the data with type
    const blob = new Blob([data], { type: 'text/csv' });
 
    // Creating an object for downloading url
    const url = window.URL.createObjectURL(blob)
 
    // Creating an anchor(a) tag of HTML
    const a = document.createElement('a')
 
    // Passing the blob downloading url
    a.setAttribute('href', url)
 
    // Setting the anchor tag attribute for downloading
    // and passing the download file name
    a.setAttribute('download', 'download.csv');
 
    // Performing a download with click
    a.click()
}
 
const csvmaker = function (data) {
 
    // Empty array for storing the values
    csvRows = [];
 
    // Headers is basically a keys of an
    // object which is id, name, and
    // profession
    const headers = Object.keys(data);
 
    // As for making csv format, headers
    // must be separated by comma and
    // pushing it into array
    csvRows.push(headers.join(','));
 
    // Pushing Object values into array
    // with comma separation
    const values = Object.values(data).join(',');
    csvRows.push(values)
 
    // Returning the array joining with new line
    return csvRows.join('\n')
}
 
const get = async function () {
 
    // JavaScript object
    const data = {
        id: 1,
        name: "Geeks",
        profession: "developer"
    }
 
    const csvdata = csvmaker(data);
    download(csvdata);
}
 
// Getting element by id and adding
// eventlistner to listen everytime
// button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);

输出: