简体   繁体   English

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

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

I am implementing Angular template for reading.CSV file and generating table.我正在实现 Angular 模板来读取.CSV 文件和生成表。 So I created two.CSV file, one for the header and second one for the table content.所以我创建了两个.CSV 文件,一个用于 header,第二个用于表格内容。

For heading CSV file: header.csv对于标题 CSV 文件:header.csv

在此处输入图像描述

For data of table CSV file: tableContent.csv对于表 CSV 文件的数据:tableContent.csv

在此处输入图像描述

Now I am able to read all data and converted into array, But I am getting into one array.现在我能够读取所有数据并转换为数组,但我正在进入一个数组。 I am sharing my code for more understanding.I have putted.csv file in assets folder.我正在分享我的代码以获得更多理解。我已将.csv 文件放入 assets 文件夹中。

app.component.ts 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 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>

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

I want to create multiple object of array.我想创建多个 object 数组。 like below:如下所示:

[{
"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"]
}]

Table heading will comes from particular header.csv and data will comes from tableContent.csv.表格标题将来自特定的 header.csv,数据将来自 tableContent.csv。 So Finally If i will click on the particular header so It will search into json object(which is read by tablecontent.csv).所以最后,如果我点击特定的 header,它将搜索 json 对象(由 tablecontent.csv 读取)。 will show the particular result.将显示特定的结果。 Like if I will click on the myAccess so related myaccess data show in the table data.就像如果我将点击 myAccess 这样相关的 myaccess 数据显示在表数据中。

Thanks in advance, Kindly share your idea.在此先感谢,请分享您的想法。

This should solve your problem.这应该可以解决您的问题。 Please handle errors better than me:D (Bootstrap being used for styling)请比我更好地处理错误:D(引导程序用于样式)

Component零件

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;
  }
}

Service服务

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' });
  }
}

sample html样品 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);        
      }
    );
  }
}

In order to remove the next line icon为了删除下一行图标
在此处输入图像描述

You need to add this line in your app.component.ts您需要在 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);
      }
    );

First we will get the header data from CSV File首先,我们将从 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);
      }
    );

In order to get the desired output, you can split the array according to your need.为了得到想要的output,可以根据需要拆分阵列。
As guess from your CSV file image, column length will be now based on this.headerData.length which will be dynamic从您的 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
 }


Read more about Array.Splice() as it help allot while creating sub-array阅读有关Array.Splice()的更多信息,因为它有助于在创建子数组时分配

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

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