gpt4 book ai didi

html - Angular 4 - 上传 CSV

转载 作者:太空狗 更新时间:2023-10-29 18:08:16 24 4
gpt4 key购买 nike

我正在制作一个 Angular4我有一个按钮可以将数据转换为带有标题的 csv 文件。现在我想反过来做,我想上传一个 csv 文件。因此,为了进行测试,我制作了一个对象并从中制作了一个 csv 文件,然后我想单击一个按钮并上传该文件并获得相同的结果。

我找到了一个导出 csv 的 angular 模块,但找不到相反的模块。有人可以帮我吗?

这是我的代码:

测试.ts

import { Component, OnInit} from '@angular/core';
import { Angular2Csv } from 'angular2-csv/Angular2-csv';
import {Unit} from "../../../_shared/unit";

@Component({
moduleId: module.id,
templateUrl: 'test.component.html',
styleUrls: ['./test.css']
})


export class TestComponent implements OnInit {



ngOnInit() {}

public export() {
// Unit (id,name,description)
var data = [new Unit(1,"Unit1","This is unit 1!")];

var options = {
fieldSeparator: ';',
quoteStrings: '"',
decimalseparator: ',',
showLabels: true,
useBom: true
};
new Angular2Csv(data, "data", options);
}

public import(){}

}

测试.html

<button (click)="export()">Download CSV</button>
<button (click)="import()">Upload CSV</button>

最佳答案

您可以使用自定义函数实现功能,试试这个:

private extractData(data) { // Input csv data to the function

let csvData = data;
let allTextLines = csvData.split(/\r\n|\n/);
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]);
}
lines.push(tarr);
}
}
console.log(lines); //The data in the form of 2 dimensional array.
}

您可以在这里找到详细的帖子:http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html#.WWxu9XV97OQ

你可以像这样在文件监听器函数中读取文件:

function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var file = files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result; // Content of CSV file
this.extractData(csv); //Here you can call the above function.
}

}

在 html 中执行此操作:

 <input type="file" (change)="handleFileSelect($event)"/>

关于html - Angular 4 - 上传 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45138466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com