繁体   English   中英

如何根据Angular中的.CSV文件的行创建多个数组?

[英]How to create multiple array based on row of .CSV file in Angular?

我正在实现 Angular 模板来读取.CSV 文件和生成表。 所以我创建了两个.CSV 文件,一个用于 header,第二个用于表格内容。

对于标题 CSV 文件:header.csv

在此处输入图像描述

对于表 CSV 文件的数据:tableContent.csv

在此处输入图像描述

现在我能够读取所有数据并转换为数组,但我正在进入一个数组。 我正在分享我的代码以获得更多理解。我已将.csv 文件放入 assets 文件夹中。

app.component.ts

export class AppComponent {
  title = 'project';
  myData: any;
  myContent: any;
  constructor(private httpClient: HttpClient) { }
  ngOnInit() {
    this.httpClient.get('assets/header.csv', { responseType: 'text' }).subscribe(
      data => {
        this.myData = data.split("\n");
      }
    );
  }
  clicked(event) {
    console.log(event.srcElement.name);
    this.httpClient.get('assets/tableContent.csv', { responseType: 'text' }).subscribe(
      data => {
        this.myContent = data.split(",");
        let ab=this.myContent;
        console.log("------------>",ab);        
      }
    );
  }
}

app.component.html

<table id="customers">
  <tr>
    <th *ngFor="let dataheader of myData"><button (click)="clicked($event)" id={{dataheader}} name={{dataheader}}>{{dataheader}}</button></th>    
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
    <td>Germany</td>
  </tr>
</table>

浏览器画面在此处输入图像描述

我想创建多个 object 数组。 如下所示:

[{
"myAccess":["myAccess","Prod","URL","a@gmail.com","Enable"]
},
{
"System":["System","Environment","URL","a@gmail.com","Enable"]
},
{
"OAM":["OAM","DEV","URL","test@gmail.com","Enable"]
},
{
"Mylogin":["Mylogin","prod","URL","s@gmail.com","Enable"]
}]

表格标题将来自特定的 header.csv,数据将来自 tableContent.csv。 所以最后,如果我点击特定的 header,它将搜索 json 对象(由 tablecontent.csv 读取)。 将显示特定的结果。 就像如果我将点击 myAccess 这样相关的 myaccess 数据显示在表数据中。

在此先感谢,请分享您的想法。

这应该可以解决您的问题。 请比我更好地处理错误:D(引导程序用于样式)

零件

import { Component, OnInit } from '@angular/core';
import { FileService } from './services/file.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  title = 'temp-app';

  public headers = [];
  public data = {};

  public selectedHeader = null;
  constructor(private fileSvc: FileService) {

  }

  ngOnInit(): void {
    this.fileSvc.getHeaders().subscribe(
      data =>  {
        if (data != null && data.length > 0) {
          let headers = data.split('\n');
          headers = headers.filter(x => x.trim() !== '');
          for (const item of headers) {
            this.headers.push(item.trim());
          }
        } else {
          this.headers = [];
        }
      }
    );

    this.fileSvc.getData().subscribe(
      data =>  {
        if (data != null && data.length > 0) {
          const tempData = data;
          let rows = [];
          rows = tempData.split('\n');
          for (let row of rows) {
            if (row.trim() === '') {
              continue;
            }
            row = row.replace('\r', '')
            const rowSplits = row.split(',');
            this.data[rowSplits[0]] = rowSplits;
          }
        } else {
          this.data = {};
        }
      });
  }

  headerSeleced(header) {
    this.selectedHeader = header;
  }
}

服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class FileService {

  constructor(private httpClient: HttpClient) {

  }

  public getHeaders() {
    return this.httpClient.get('assets/header.csv', { responseType: 'text' });
  }

  public getData() {
    return this.httpClient.get('assets/tableContent.csv', { responseType: 'text' });
  }
}

样品 html

<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <h3>Headers</h3>
    </div>
    <div *ngFor="let item of headers"
      class="col-sm-3 bg-secondary p-2 m-1 text-white btn"
      (click)="headerSeleced(item)">
      {{item}}
    </div>
  </div>
  <hr>
  <div class="row">
    <ng-container *ngFor="let item of data | keyvalue">
      <ng-container *ngIf="selectedHeader == item.key" >
        <div class="col-auto border">
          <b>{{item.key}}</b>
        </div>
        <div *ngFor="let prop of item.value" class="col-auto border">
          {{prop}}
        </div>
      </ng-container>
    </ng-container>
  </div>
</div>
export class AppComponent {
  title = 'project';
  myData: any;
  myContent = [];
  constructor(private httpClient: HttpClient) { }
  ngOnInit() {
    this.httpClient.get('assets/header.csv', { responseType: 'text' }).subscribe(
      data => {
        this.myData = data.split("\n");
      }
    );
  }
  clicked(event) {
    console.log(event.srcElement.name);
    this.httpClient.get('assets/tableContent.csv', { responseType: 'text' }).subscribe(
      data => {
        this.myContent.push({event.srcElement.name: data.split(",")});
        let ab=this.myContent;
        console.log("------------>",ab);        
      }
    );
  }
}

为了删除下一行图标
在此处输入图像描述

您需要在 app.component.ts 中添加这一行

this.httpClient.get('assets/content.csv', { responseType: 'text' }).subscribe(
      data => {
             // add this line before the split
              data = data.replace(/[\r\n]/g,",");
             this.headerData = data.split(",").filter(Boolean);
      }
    );

首先,我们将从 CSV 文件中获取 header 数据

this.httpClient.get('assets/header.csv', { responseType: 'text' }).subscribe(
      data => {
             // add this line before the split
              data = data.replace(/[\r\n]/g,",");
             this.headerData = data.split(",").filter(Boolean);
      }
    );

为了得到想要的output,可以根据需要拆分阵列。
从您的 CSV 文件图像中猜测,列长度现在将基于 this.headerData.length 这将是动态的

 for( let index = 0; index < this.myContent.length; index ++) {
           const value = this.myContent.splice(0,this.headerData.length);
          // now you got the value you can create structure according to your need
 }


阅读有关Array.Splice()的更多信息,因为它有助于在创建子数组时分配

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM