JavaScript 如何创建和下载CSV文件
有时我们需要以CSV文件的形式获取数据,这可能是用户的详细信息或其他用于机器学习或分析目的的数据。我们可以轻松地从任何javascript对象或JSON文件中获取数据,并以CSV文件的形式下载。
在本文中,我们将处理两个数据源:
- Javascript对象
- JSON对象
数据源:Javascript对象
方法: 简而言之,我们需要头部,这由javascript对象的键引用,并且需要以逗号分隔来构成CSV文件的行,这些行由javascript对象的值引用。我们使用Blob来构建CSV文件。
// Javascript Object
const data = {
id: 1,
name: "Geeks",
profession: "developer"
}
这应该被转换为:
id, name, profession
1, Geeks, developer
步骤 1: 设置项目
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<button id="action">Download csv</button>
<script type="text/javascript"
src="main.js"></script>
</body>
</html>
main.js
const get = async function () {
// JavaScript bject
const data = {
id: 1,
name: "Geeks",
profession: "developer"
}
}
// Getting element by id and adding eventlistener
// to listen everytime button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);
步骤 2: 在main.js中创建一个csvmaker函数。该函数负责将普通的Java对象转换为CSV格式。
main.js
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"
}
console.log(csvmaker(data));
}
// Getting element by id and adding
// eventlistener to listen everytime
// button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);
输出:
步骤 3: 创建一个下载函数。这个函数将使我们能够下载一个包含我们传入数据的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
// eventlistener 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);
}
- 我们需要循环遍历对象值并将它们推送到数组中的 csvmaker函数在main.js中
Javascript
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[0]);
// As for making csv format, headers must be
// separated by comma and pushing it into array
csvRows.push(headers.join(','));
// Pushing Object values into the array with
// comma separation
// Looping through the data values and make
// sure to align values with respect to headers
for (const row of data) {
const values = headers.map(e => {
return row[e]
})
csvRows.push(values.join(','))
}
// const values = Object.values(data).join(',');
// csvRows.push(values)
// returning the array joining with new line
return csvRows.join('\n')
}
输出: