以表格/ csv格式显示逗号分隔的HTML字符串

Que*_*Que 2 html javascript css csv angular

我有一个用逗号分隔的Typescript文件中内置的字符串。可以将其导出为“ file.csv”,下载后所有内容均可正确显示。

我要实现的是在下载此字符串之前为其创建“预览”。我希望预览类似于HTML表格,或它在CSV中的显示方式。

示例字符串

1,Header1, Header2, Header3, Header4,
2,0,1,"Content","More Content","
Run Code Online (Sandbox Code Playgroud)

自然,在CSV中,其外观与上述相同,但在边框/单元格中分隔。

是否可以用HTML实现呢?

Tha*_*guy 6

这是我在stackblitz上创建的示例:https ://stackblitz.com/edit/angular-k162aa

CSV的主要解析功能在下面用内联注释描述:

// CSV is assumed to have headers as well
csvToJSON(csv: string) {

  const lines: string[] = csv
    // escape everything inside quotes to NOT remove the comma there
    .replace(/"(.*?)"/gm, (item) => encodeURIComponent(item))
    // split by lines
    .split('\n');

  // separate the headers from the other lines and split them
  const headers: string[] = lines.shift().split(',');

  // should contain all CSV lines parsed for the html table
  const data: any[] = lines.map((lineString, index) => {
    const lineObj = {};

    const lineValues = lineString.split(',');

    headers.forEach((valueName, index) => {
      // remove trailing spaces and quotes
      lineObj[valueName] = lineValues[index]
        // handle quotes
        .replace(/%22(.*?)%22/gm, (item) => decodeURIComponent(item))
        // trim trailing spaces
        .trim();
    })

    return lineObj; // return lineValues for array representation.
  }); 

  return { data, headers };
}

csvToJSON(csv: string) {

  const lines: string[] = csv.split('\n');

  // separate the headers from the other lines and split them
  const headers: string[] = lines.shift().split(',');

  // should contain all CSV lines parsed for the html table
  const data: string[][] = lines.map((lineString, index) => {
    const lineObj = {};

    const lineValues = lineString.split(',');

    headers.forEach((valueName, index) => {
      lineObj[valueName] = lineValues[index];
    });

    return lineObj; // return lineValues for an array.
  }); 

  return { data, headers };
}
Run Code Online (Sandbox Code Playgroud)

请注意,注释的代码可以为您提供一个数组数组,而该代码按原样返回对象数组。

在HTML中,此格式更易于呈现,因为标头的索引与每个项目数组的索引相同:

<table class="table">
  <thead>
    <tr>
      <th *ngFor="let header of headers">{{ header }}</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of data">
      <td *ngFor="let header of headers">
        {{ row[header] }}
      </td>
    </tr>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

要支持行标题,可以在表主体部分使用以下html代码段:

<tr *ngFor="let row of data">
  <ng-container *ngFor="let attribute of row; let i = index">
    <td *ngIf="i">{{ attribute }}</td>
    <th *ngIf="!i">{{ attribute }}</th>
  </ng-container>
</tr>
Run Code Online (Sandbox Code Playgroud)