簡體   English   中英

角度 5:如何將數據導出到 csv 文件

[英]ANGULAR 5 : how to export data to csv file

我是 angular 的初學者,我正在研究 Angular 5, Node v8.11.3。

我想實現一個接受參數數據和標題的通用函數。 並作為輸出一個 csv 文件。

我創建了一個名為“ FactureComponent ”的組件,然后我生成了一個名為“ DataService ”的服務,然后我創建了一個 getFactures 函數,該函數從模擬中檢索我的項目列表,它運行良好。

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { FACTURES } from '../mock.factures';

@Component({
selector: 'app-facture',
templateUrl: './facture.component.html',
styleUrls: ['./facture.component.scss']
})
export class FactureComponent implements OnInit {

factures = [];
columns  = ["Id","Reference","Quantite","Prix Unitaire"];
btnText:  String = "Export CSV";

constructor(private _data: DataService) { }

ngOnInit() {
this.getFactures();
}
getFactures(){
this.factures=this._data.getFactures();
}
generateCSV(){
console.log("generate");
}
}

您會在視圖下方找到

<form>
<input type="submit" [value]="btnText" (click)="generateCSV()"/>
</form>

<table>
 <tr>
   <th *ngFor="let col of columns">
      {{col}}
   </th>
 </tr>
 <tr *ngFor="let facture of factures">
  <td>{{facture.id}}</td>     
  <td>{{facture.ref}}</td>
  <td>{{facture.quantite}}</td>
  <td>{{facture.prixUnitaire}}</td>
 </tr>
</table>

所以我想實現一個功能,將我在視圖上顯示的數據轉換成一個csv文件。

更新:這里有更好的方法:

  1. 在項目目錄中打開命令提示符。
  2. 通過鍵入npm install --save file-saver
  3. import { saveAs } from 'file-saver/FileSaver'; 進入您的 .ts 文件。
  4. 這是基於新導入的更新代碼。

downloadFile(data: any) {
    const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
    const header = Object.keys(data[0]);
    let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
    csv.unshift(header.join(','));
    let csvArray = csv.join('\r\n');

    var blob = new Blob([csvArray], {type: 'text/csv' })
    saveAs(blob, "myFile.csv");
}

歸功於此將對象轉換為 CSV 的答案

下面是使用方法:

downloadFile(data: any) {
  const replacer = (key, value) => (value === null ? '' : value); // specify how you want to handle null values here
  const header = Object.keys(data[0]);
  const csv = data.map((row) =>
    header
      .map((fieldName) => JSON.stringify(row[fieldName], replacer))
      .join(',')
  );
  csv.unshift(header.join(','));
  const csvArray = csv.join('\r\n');

  const a = document.createElement('a');
  const blob = new Blob([csvArray], { type: 'text/csv' });
  const url = window.URL.createObjectURL(blob);

  a.href = url;
  a.download = 'myFile.csv';
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove();
}

如果我找到更好的方法,我會稍后補充。

我的解決方案目前正在為儲蓄提供服務(我從Changhui Xu @ codeburst那里得到了這個)。 這個不需要安裝包...

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root',
})
export class CsvDataService {
    exportToCsv(filename: string, rows: object[]) {
      if (!rows || !rows.length) {
        return;
      }
      const separator = ',';
      const keys = Object.keys(rows[0]);
      const csvContent =
        keys.join(separator) +
        '\n' +
        rows.map(row => {
          return keys.map(k => {
            let cell = row[k] === null || row[k] === undefined ? '' : row[k];
            cell = cell instanceof Date
              ? cell.toLocaleString()
              : cell.toString().replace(/"/g, '""');
            if (cell.search(/("|,|\n)/g) >= 0) {
              cell = `"${cell}"`;
            }
            return cell;
          }).join(separator);
        }).join('\n');

      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
      } else {
        const link = document.createElement('a');
        if (link.download !== undefined) {
          // Browsers that support HTML5 download attribute
          const url = URL.createObjectURL(blob);
          link.setAttribute('href', url);
          link.setAttribute('download', filename);
          link.style.visibility = 'hidden';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      }
    }
  }

然后我在我的組件中注入這個服務。 然后它調用這個服務:


  constructor(private csvService :CsvDataService) {}

  saveAsCSV() {
    if(this.reportLines.filteredData.length > 0){
      const items: CsvData[] = [];

      this.reportLines.filteredData.forEach(line => {
        let reportDate = new Date(report.date);
        let csvLine: CsvData = {
          date: `${reportDate.getDate()}/${reportDate.getMonth()+1}/${reportDate.getFullYear()}`,
          laborerName: line.laborerName,
          machineNumber: line.machineNumber,
          machineName: line.machineName,
          workingHours: line.hours,
          description: line.description
        }
        items.push(csvLine); 
      });

      this.csvService.exportToCsv('myCsvDocumentName.csv', items);
    }

  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM