Javascript 如何逐行读取angular2上的csv文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46744611/
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
How to read a csv file on angular2 line by line
提问by asmmahmud
I am programming an application in angular2 that reads a csv file with a simply input in html:
我正在 angular2 中编写一个应用程序,该应用程序使用 html 中的简单输入读取 csv 文件:
<input type='file' name='userFile' id='file' >
I can acces to the file at the component.ts:
我可以访问 component.ts 中的文件:
ngOnInit() {
var input = (<HTMLInputElement>document.getElementById("file"));
input.addEventListener("change", function(event) {
var files = input.files;
var len = files.length;
if (len) {
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
}
}, false);
}
How can I read cell by cell a csv file uploaded using typescript, javascript or jquery? (and wich is the best way to do it).
如何逐个读取使用打字稿、javascript 或 jquery 上传的 csv 文件?(这是最好的方法)。
回答by asmmahmud
Here is a example implementation angular way:
这是一个示例实现角度方式:
@Component({
selector: 'app-my-file',
template: `
<div class="form-group">
<input type="file" (change)="onFileSelect($event.target)" name="myfile">
</div>
`,
styles: [``]
})
export class YourComponent implements OnInit {
csvContent: string;
constructor(){}
ngOnInit(){
}
onFileLoad(fileLoadedEvent) {
const textFromFileLoaded = fileLoadedEvent.target.result;
this.csvContent = textFromFileLoaded;
// alert(this.csvContent);
}
onFileSelect(input: HTMLInputElement) {
const files = input.files;
var content = this.csvContent;
if (files && files.length) {
/*
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
*/
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.readAsText(fileToLoad, "UTF-8");
}
}
}
回答by Matt
In addition to asmmahmud's answer, I'd like to add how you can actually parse the file content so you have rows and columns in an array (Angular with TypeScript). Add the property:
除了asmmahmud 的回答之外,我还想补充一下如何实际解析文件内容,以便在数组中包含行和列(Angular with TypeScript)。添加属性:
parsedCsv: string[][];
to the class YourComponentin his example.
Then, update the onFileLoadevent as follows:
到YourComponent他的例子中的班级 。然后,更新onFileLoad事件如下:
onFileLoad(fileLoadedEvent): void {
const csvSeparator = ';';
const textFromFileLoaded = fileLoadedEvent.target.result;
this.csvContent = textFromFileLoaded;
// alert(textFromFileLoaded);
const txt = textFromFileLoaded;
const csv = [];
const lines = txt.split('\n');
lines.forEach(element => {
const cols: string[] = element.split(csvSeparator);
csv.push(cols);
});
this.parsedCsv = csv;
// console.log(this.parsedCsv);
}
Now you have the parsed CSV with its lines and columns in the two-dimensional array parsedCsv(1st dimension is the rows, 2nd dimension the column). You can replace the separator if required - default is semicolon.
现在您已解析 CSV 及其二维数组中的行和列parsedCsv(第一维是行,第二维是列)。如果需要,您可以替换分隔符 - 默认为分号。
Example:
例子:
A file containing
一个文件包含
A;B;C
1;2,300;3
4;5.5;6
A;B;C
1;2,300;3
4;5.5;6
produces the following data structure in parsedCsv
产生以下数据结构 parsedCsv
You can see that if your file contains column headers, then the data starts with row index 1, otherwise (without column headers) with row index 0.
您可以看到,如果您的文件包含列标题,则数据以行索引 1 开头,否则(没有列标题)以行索引 0 开头。
Note:On Stackblitz, I have added the following few lines so you can see how the array is populated:
注意:在 Stackblitz 上,我添加了以下几行,以便您可以查看数组是如何填充的:
// demo output as alert
var output: string="";
csv.forEach(row => {
output += "\n";
var colNo = 0;
row.forEach(col => {
if (colNo>0) output += " | ";
output += col;
colNo++;
});
});
alert(output);
回答by Mahendra Waykos
csv2Array(fileInput: any){
//read file from input
this.fileReaded = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.readAsText(this.fileReaded);
reader.onload = (e) => {
let csv: string = reader.result;
let allTextLines = csv.split(/\r|\n|\r/);
let headers = allTextLines[0].split(',');
let lines = [];
for (let i = 0; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
if (data.length === headers.length) {
let tarr = [];
for (let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
// log each row to see output
console.log(tarr);
lines.push(tarr);
}
}
// all rows in the csv file
console.log(">>>>>>>>>>>>>>>>>", lines);
} }
回答by Mahendra Waykos
I found a way to extract the text:
我找到了一种提取文本的方法:
var fr = new FileReader();
fr.onload = function(e) {
var text = fr.result;
console.log(text);
};
fr.readAsText(files[0]);
And then using split separate rows and cells into arrays:
然后使用将单独的行和单元格拆分为数组:
var rows = text.split("\n");
console.log("Row 0 " + rows[0]);
console.log("Row 1 " + rows[1]);
console.log("Row 2 " + rows[2]);
var row1 = rows[0].split(";");
console.log("Value 0,0 " + row1[0]);
console.log("Value 0,1 " + row1[1]);
console.log("Value 0,2 " + row1[2]);
*This code doesn't work well if cells contain ";" characters, wich is not the case of my application.
*如果单元格包含“;”,则此代码无法正常工作 字符,这不是我的应用程序的情况。


