将 csv 文件加载到 jQuery 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7654196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading csv file into jQuery?
提问by Richard
I have a CSV file that I would like to use as source data for a jQuery flot graph.
我有一个 CSV 文件,我想将其用作 jQuery 浮点图的源数据。
Should I:
我是不是该:
- Find a jQuery plugin that will load the CSV file directly?
- Convert the CSV file into JSON and use that instead?
- Do something completely different?
- 找到一个可以直接加载CSV文件的jQuery插件?
- 将 CSV 文件转换为 JSON 并使用它?
- 做一些完全不同的事情?
I'm not having much luck finding a jQuery plugin that can cope with an external CSV file, but maybe I'm missing something.
我没有太多运气找到可以处理外部 CSV 文件的 jQuery 插件,但也许我遗漏了一些东西。
采纳答案by Chris G.
Use the jQuery CSV plugin to get an array. Build / sort the array however you need for the chart.
使用 jQuery CSV 插件获取数组。构建/排序数组,但您需要图表。
It just occured to me you may be thinking of reading a flat CSV file with jQuery. That's not possible. Giving javascript access to the filesystem sounds like a terrible idea. You can always use $.get()
to load a file on a server, though.
我突然想到您可能正在考虑使用 jQuery 读取平面 CSV 文件。那是不可能的。让 javascript 访问文件系统听起来像是一个糟糕的主意。不过,您始终可以使用$.get()
在服务器上加载文件。
回答by Evan Plaice
No server required...
不需要服务器...
This can be accomplished without the server if you employ a little ingenuity.
如果您运用一点独创性,这可以在没有服务器的情况下完成。
You'll need 2 things:
你需要两件事:
- A browser that is HTML5 File APIcapable
- The jQuery-CSVlibrary
- 浏览器是HTML5文件API能够
- 在jQuery的CSV库
The jquery-csv parser library specializes in parsing RFC 4180compliant CSV, with many capabilities above and beyond just transforming CSV data into JavaScript data. For the purpose of this demonstration we're going to use two features:
jquery-csv 解析器库专门解析符合RFC 4180 的CSV,除了将 CSV 数据转换为 JavaScript 数据之外,还有许多功能。出于本演示的目的,我们将使用两个功能:
The first is the toArrays() method. It takes a multi-line CSV string and transforms it into a 2D array.
第一个是 toArrays() 方法。它采用多行 CSV 字符串并将其转换为二维数组。
The second is a user-defined parser hook that automatically transforms the output (which is all strings) into scalar (ie integer/float) data. Basically, through the use of a function callback, it's possible to inline additional processing into the parser.
第二个是用户定义的解析器钩子,它自动将输出(所有字符串)转换为标量(即整数/浮点数)数据。基本上,通过使用函数回调,可以将附加处理内联到解析器中。
Once you have the CSV data assigned to a string variable the transform to JavaScript data is very simple.
将 CSV 数据分配给字符串变量后,转换为 JavaScript 数据非常简单。
var csv = "" // this is the string containing the CSV data
var data = $.csv.toArray(csv, {
onParseValue: $.csv.hooks.castToScalar
});
That's all for the CSV parsing step.
这就是 CSV 解析步骤的全部内容。
Now, what Flot expects is an array of 2D arrays where each 2D array contains an independent dataset.
现在,Flot 期望的是一个二维数组数组,其中每个二维数组包含一个独立的数据集。
To build your data create an empty array first:
要构建您的数据,请先创建一个空数组:
var flotData = [];
Then for each data set you generate using CSV you simply add the dataset to the collection.
然后对于您使用 CSV 生成的每个数据集,您只需将数据集添加到集合中。
var flotData.push(data);
File handling via HTML5 is a tricky topic because it uses asynchronous callbacks to load files; that means no return statements. To keep things simple, I'll just make the flot plot a global object.
通过 HTML5 处理文件是一个棘手的话题,因为它使用异步回调来加载文件;这意味着没有返回语句。为简单起见,我只会让散点图成为一个全局对象。
First initialize the plot during the $(document).ready():
首先在 $(document).ready() 期间初始化绘图:
var data = [];
flot = $.flot($('#plotdiv'), data, options);
Note: A dummy data object is added so the graph can be initialized.
注意:添加了一个虚拟数据对象,以便可以初始化图形。
Then, add a file handler:
然后,添加一个文件处理程序:
// handles csv files
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// reset the flot dataset
flot.setData([]);
for(var i=0, len=files.length; i<len; i++) {
flotFileData(files[i], i);
}
}
Assume that this can load one-or-more CSV data files. This gets called after you choose your files from the file dialog. The data gets reset to empty (ie []) because we want to start fresh after every time the file dialog gets executed; otherwise you'll be appending to a previous dataset.
假设这可以加载一个或多个 CSV 数据文件。从文件对话框中选择文件后会调用此方法。数据被重置为空(即 []),因为我们想在每次文件对话框执行后重新开始;否则,您将附加到以前的数据集。
This will cycle through the files and call flotFileData() for each file that was selected in the file dialog..
这将循环浏览文件并为在文件对话框中选择的每个文件调用 flotFileData()。
Here's the code for handling the file open callback:
下面是处理文件打开回调的代码:
function flotFileData(file, i) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var newData = $.csv.toArrays(csv, {
onParseValue:$.csv.hooks.castToScalar
});
var data = flot.getData();
data[i] = newData;
flot.setData(data);
flot.setupGrid();
flot.draw();
};
reader.onerror = function(){ alert('Unable to read ' + file.fileName); };
}
This reads the file as plain-text and makes the contents available via event.target.result. The CSV parser transforms the CSV to scalar data in 2-dimensional array form. To stack multiple datasets we need to append to the data that's already in the plot, so we need to store the existing data first via flot.getData(). Append the new data, set it via flot.setData() and finally re-draw the plot.
这会将文件作为纯文本读取,并通过 event.target.result 使内容可用。CSV 解析器将 CSV 转换为二维数组形式的标量数据。要堆叠多个数据集,我们需要附加到图中已有的数据,因此我们需要首先通过 flot.getData() 存储现有数据。追加新数据,通过 flot.setData() 进行设置,最后重新绘制绘图。
Note: If the ranges of the graph don't need to be re-calculated you can skip the flot.setupGrid() call.
注意:如果不需要重新计算图形的范围,您可以跳过 flot.setupGrid() 调用。
Ideally, the redraw should only happen once per file loading phase but this demo hasn't been optimized yet. That means, the graph will be re-drawn for every file that's read (definitely not ideal).
理想情况下,重绘应该在每个文件加载阶段只发生一次,但此演示尚未优化。这意味着,将为读取的每个文件重新绘制图形(绝对不理想)。
If you want to see it in action, take a look at the 'Flot Demonstration' provided by the jquery-csv project. I suggest you try loading both the analytics1.csv and analytics2.csv datasets so you can see how both are overlaid on the graph.
如果您想看到它的实际效果,请查看jquery-csv 项目提供的“ Flot Demonstration”。我建议您尝试同时加载 analytics1.csv 和 analytics2.csv 数据集,以便您可以看到两者在图形上的重叠情况。
If you decide to go the server-side route to load the CSV files, there's also a more basic example that demonstrates loading the CSV from a textarea.
如果您决定使用服务器端路由来加载 CSV 文件,还有一个更基本的示例演示从文本区域加载 CSV。
Disclaimer: I am the author of jquery-csv.
免责声明:我是 jquery-csv 的作者。
Update:
更新:
Due to the shuttering of Google Code, jquery-csv has been moved to GitHub
由于 Google Code 关闭,jquery-csv 已移至 GitHub