javascript - 如何将数据从 csv 文件或 excel 文件导出到 javascript 对象?
问题描述
我想知道是否有办法将数据从 CSV 文件导出到 javascript 对象,当有人编辑 CSV 文件时,它会在 javascript 文件中自动更改。非常感谢。
解决方案
以下步骤在下面的代码片段中实现。根据需要自定义。
- 选择输入 CSV 文件。(代码片段针对 UTF-8 编码的 CSV 文件进行了测试)
- 读取 CSV 文件数据
- 解析 CSV 文件数据并构造 JSON 对象
- 如果需要,操作或修改 JSON 对象。
- 将 JSON 对象导出为 CSV
var CsvRows;
var headers;
// This event will be triggered when file is selected
// Note: This code is tested for UTF-8 encoded CSV file
function handleChange(evt) {
var reader = new FileReader();
reader.onload = function() {
//reader.result gives the file content
document.getElementById('out').innerHTML = reader.result;
//parse the result into javascript object
var lines = reader.result.split('\r\n');
headers = lines[0].split(',');
lines.shift();
CsvRows = lines.map((item) => {
var values = item.split(',');
var row = {};
headers.map((h, i) => {
row[h] = values[i];
});
return row;
});
console.log(CsvRows);
document.getElementById('result').style.display = 'block'
};
//read the selected file
reader.readAsBinaryString(evt.files[0]);
};
//export the javscript object as csv
function exportCSV() {
//contruct the csv ad data url
let csvContent = "data:text/csv;charset=utf-8," +
headers.join(",") + "\r\n";
//contruct the data in csv format
var data = CsvRows.map(e => {
var line = '';
headers.map((h) => {
line += e[h] + ',';
});
return line.substr(0, line.length - 1);
}).join("\r\n")
csvContent += data;
//contruct an anchor tag
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
//provide the export file name
link.setAttribute("download", "mydata.csv");
document.body.appendChild(link); // Required for FF
//trigger download of CSV
link.click();
link.remove();
}
<input type="file" onchange="handleChange(this)" accept=".csv" />
<div id="result" style="display:none;">
<div id="out"></div>
<div>See console for Javascript Object.</div>
<div>Export the imported file <button onclick="exportCSV()">Export</button></div>
</div>
上面的代码片段仅适用于 CSV 文件。必须对 Excel 文件进行自定义实现。
推荐阅读
- coq - Coq 中的 Bove-Capretta 方法
- bash - 'docker ps' 输出格式:仅列出正在运行的容器的名称
- c++ - 如何初始化模板类的哨兵节点的值?
- mariadb - MariaDB 和 HAProxy(集群)的连接问题
- c# - 符号表是存储 AST(声明)节点还是“符号”是不同的对象/类?
- symfony - 如何在 phpunit 功能测试中模拟自动连接到 symfony 控制器的服务?
- c# - 在区间 [1000,9999] 中查找素数的更好解决方案,其中第一个和第二个之和
- node.js - NodeJS 视频流动态转码
- python - 从子进程获取无缓冲的输出无法正常工作 Python
- php - 如何使用 xero API 设置跟踪类别选项?