bre*_*one 4 csv json data-conversion format-conversion angular
想使用papa-parse-angular2将CSV转换为JSON.没有找到任何例子所以我这样做.
app.module.ts
import {CSVService} from 'papa-parse-angular2';
@NgModule({
providers: [
CSVService, ...
Run Code Online (Sandbox Code Playgroud)
xx.component.ts
constructor( private csvService: CSVService, ...
private x1() {
let file = ...;
this.csvService.parse(file, {
complete: function(results) {
// take results.data
}
});
Run Code Online (Sandbox Code Playgroud)
Uncaught TypeError: Cannot read property 'length' of undefined
at CSVHandler.guessHeaders (vendor.bundle.js:105749)
at CSVHandler.formHeaders (vendor.bundle.js:105734)
at CSVHandler.setHeaders (vendor.bundle.js:105761)
at vendor.bundle.js:64297
at ZoneDelegate.invoke (vendor.bundle.js:137052)
at Object.onInvoke (vendor.bundle.js:4532)
at ZoneDelegate.invoke (vendor.bundle.js:137051)
at Zone.run (vendor.bundle.js:136812)
at NgZone.run (vendor.bundle.js:4401)
at vendor.bundle.js:64293
at SafeSubscriber.schedulerFn [as _next] (vendor.bundle.js:4247)
at SafeSubscriber.__tryOrUnsub (vendor.bundle.js:14620)
at SafeSubscriber.next (vendor.bundle.js:14569)
at Subscriber._next (vendor.bundle.js:14509)
at Subscriber.next (vendor.bundle.js:14473)
at EventEmitter.Subject.next (vendor.bundle.js:15308)
at EventEmitter.emit (vendor.bundle.js:4221)
Run Code Online (Sandbox Code Playgroud)
不知道如何解决.或其他libs将CSV转换为角度为4的JSON?感谢任何帮助.
你可以使用ngx-papaparse.
首先安装库:
对于Angular 6(docs):
npm install ngx-papaparse --save
还有Angular 2/4和Angular 5的版本.
然后将其导入您的模块(不必是您的AppModule):
import { PapaParseModule } from 'ngx-papaparse';
@NgModule({
...
imports: [
...
PapaParseModule
]
})
Run Code Online (Sandbox Code Playgroud)
解析CSV:
import { Component } from '@angular/core';
import { Papa } from 'ngx-papaparse';
@Component({
...
})
export class AppComponent {
constructor(private papa: Papa) {
let csvData = '"Hello","World!"';
this.papa.parse(csvData,{
complete: (result) => {
console.log('Parsed: ', result);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以解析文件而不是字符串.只需替换csvData文件即可.
免责声明:我创建了这个库.
小智 4
您可以简单地使用papaparser。
import * as Papa from 'papaparse/papaparse.min.js';
Run Code Online (Sandbox Code Playgroud)
使用
onUpload(file: File) {
Papa.parse(file, {
complete: function(results) {
console.log("Finished:", results.data);
}
});
}
Run Code Online (Sandbox Code Playgroud)
然而,一个缺点是你不会得到 papaparse 的任何类型定义
| 归档时间: |
|
| 查看次数: |
4275 次 |
| 最近记录: |