javascript - 服务器端 CSV 文件将其转换为 JavaScript 数组
问题描述
我正在开发一个需要能够更新 HTML 表格的项目,我会通过 javascript 来完成。我还没有为这个项目创建一个 HTML 站点,因为我会尝试将 CSV 文件转换为 Java 数组,这将更新 HTML 表。
我一直在尝试使用 papa parse,但它对我不起作用。我没有使用 npm 和安装和让东西像 Papa parsa 一样工作的经验。我找到了这个网站,它具有将 CSV 转换为数组的强大功能。这个函数的一个问题是,我不能在服务器上获取一个本地文件,然后像处理字符串一样将它放入函数中。也许我忽略了一些东西?
我已经让 Papa Parse 以某种方式工作,但我不知道如何在本地文件上使用它,所以我有两个代码可以完成这项工作,但我不知道如何让他们去做或者有多好结果是。
我刚刚得到一个随机的 CSV 文件作为测试文件。Normal.csv 来自 papa parse 网站。
--总结一下-- 我想获取一个 CSV 文件,将其转换为 Java 数组,然后将其转换为 HTML 表
这是我的长 HTML 文件,包含所有脚本——此时没有 CSS。
文件托管在本地 Apache/XAMPP 服务器上。
<head>
<title>Test af Papa Parse</title>
</head>
<body>
<p>Hey - Test paraghaph</p>
<script src="node_modules/papaparse/papaparse.min.js"></script>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
/*edit: src="http://localhost/test/node_modules/papaparse/papaparse.min.js"*/
/*edit: src="http://localhost/test/node_modules/jquery/dist/jquery.min.js"*/
<script>
var config = {
download: true,
// rest of config ...
delimiter: "", // auto-detect
newline: "", // auto-detect
quoteChar: '"',
escapeChar: '"',
header: false,
trimHeaders: false,
dynamicTyping: false,
preview: 0,
encoding: "",
worker: false,
comments: false,
step: undefined,
complete: undefined,
error: undefined,
download: false,
skipEmptyLines: false,
chunk: undefined,
fastMode: undefined,
beforeFirstChunk: undefined,
withCredentials: undefined,
transform: undefined
}
var data = csv2array("http://localhost/test/normal.csv")
var data2 = Papa.parse("http://localhost/test/normal.csv", config)
console.log("papa parsa - direktly: "+ Papa.parse("http://localhost/test/normal.csv", config))
console.log(data)
console.log("data2 = "+data2)
console.log(data2);
/**
* Convert data in CSV (comma separated value) format to a javascript array.
*
* Values are separated by a comma, or by a custom one character delimeter.
* Rows are separated by a new-line character.
*
* Leading and trailing spaces and tabs are ignored.
* Values may optionally be enclosed by double quotes.
* Values containing a special character (comma's, double-quotes, or new-lines)
* must be enclosed by double-quotes.
* Embedded double-quotes must be represented by a pair of consecutive
* double-quotes.
*
* Example usage:
* var csv = '"x", "y", "z"\n12.3, 2.3, 8.7\n4.5, 1.2, -5.6\n';
* var array = csv2array(csv);
*
* Author: Jos de Jong, 2010
*
* @param {string} data The data in CSV format.
* @param {string} delimeter [optional] a custom delimeter. Comma ',' by default
* The Delimeter must be a single character.
* @return {Array} array A two dimensional array containing the data
* @throw {String} error The method throws an error when there is an
* error in the provided data.
*/
function csv2array(data, delimeter) {
// Retrieve the delimeter
if (delimeter == undefined)
delimeter = ',';
if (delimeter && delimeter.length > 1)
delimeter = ',';
// initialize variables
var newline = '\n';
var eof = '';
var i = 0;
var c = data.charAt(i);
var row = 0;
var col = 0;
var array = new Array();
while (c != eof) {
// skip whitespaces
while (c == ' ' || c == '\t' || c == '\r') {
c = data.charAt(++i); // read next char
}
// get value
var value = "";
if (c == '\"') {
// value enclosed by double-quotes
c = data.charAt(++i);
do {
if (c != '\"') {
// read a regular character and go to the next character
value += c;
c = data.charAt(++i);
}
if (c == '\"') {
// check for escaped double-quote
var cnext = data.charAt(i+1);
if (cnext == '\"') {
// this is an escaped double-quote.
// Add a double-quote to the value, and move two characters ahead.
value += '\"';
i += 2;
c = data.charAt(i);
}
}
}
while (c != eof && c != '\"');
if (c == eof) {
throw "Unexpected end of data, double-quote expected";
}
c = data.charAt(++i);
}
else {
// value without quotes
while (c != eof && c != delimeter && c!= newline && c != ' ' && c != '\t' && c != '\r') {
value += c;
c = data.charAt(++i);
}
}
// add the value to the array
if (array.length <= row)
array.push(new Array());
array[row].push(value);
// skip whitespaces
while (c == ' ' || c == '\t' || c == '\r') {
c = data.charAt(++i);
}
// go to the next row or column
if (c == delimeter) {
// to the next column
col++;
}
else if (c == newline) {
// to the next row
col = 0;
row++;
}
else if (c != eof) {
// unexpected character
throw "Delimiter expected after character " + i;
}
// go to the next character
c = data.charAt(++i);
}
return array;
}
</script>
</body>
解决方案
您不需要整个库来解析 CSV,这是我能想到的最简单的格式。通过ajax获取文件,然后使用这些函数之一进行 CSV → 数组转换。
var CSVContent = `column1, column2, column3
1, 2, hello
3, 4, world`;
function CSVToArrayOfArray(content) {
return content
.split('\r\n').join('\n') // CRLF -> LF
.split('\n')
.map(line => line.split(',').map(value => value.trim()));
}
function CSVToArrayOfObjects(content) {
let ret = CSVToArrayOfArray(content)
.map((arr, index, all) => {
if (index==0) {
return arr;
}
let obj = {};
all[0].forEach((field, i) => obj[field] = arr[i])
return obj;
});
ret.shift();
return ret;
}
console.log(CSVToArrayOfArray(CSVContent));
console.log(CSVToArrayOfObjects(CSVContent));
推荐阅读
- python - 在 RASA Core/NLU 中获取意图值
- email - 使用从 PL/SQL PROC 中提取的数据通过电子邮件发送报告
- ios - 如何在 UIView 上实现圆边效果?我附上了一张示例图片
- angular - Angular 根据用户输入动态更改组件数组
- javascript - 在 XML 中搜索一个单词并仅使用 javascript 显示该节点
- c# - 将 Excel 文件导入 DataGridView,然后将 DataGridView 更新为数据库(使用 C# 和 Visual Studio)
- java - Firebase android获取对象的值不为null,但获取对象的属性返回null
- telerik - 用于角度网格的 Kendo,可在组内分组操作数据
- python - 使用 .iterrows() 和 series.nlargest() 来获取数据帧中一行中的最高数字
- python - 将前行详细信息存储在 Dataframe 中的字典列表中