如何在角度4中导入CSV文件并在数据库中导入存储的数据?

时间:2017-12-06 11:58:49

标签: node.js angular angular2-forms

我想以角度4导入CSV,并将数据存储在我的数据库中。

<input type="file" name="importCSV">
<button type="submit" class="btn btn-primary">Submit</button>

当我点击提交按钮时,我想将数据存储在我的表格中。

2 个答案:

答案 0 :(得分:3)

这是html代码。

<input type="file" #fileImportInput name="File Upload" (change)="csvChanged($event)" id="txtFileUpload">
  

下面是我的组件代码

const CSVConstants = {
   tokenDelimeter: ",",
   isHeaderPresentFlag: true,
   validateHeaderAndRecordLengthFlag: true,
   valildateFileExtenstionFlag: true,
}

public csvChanged(event) {
    var files = event.target.files;

    if (CSVConstants.validateHeaderAndRecordLengthFlag) {
        if (!this.fileUtil.isCSVFile(files[0])) {
            this.utilService.showToastMsg("error", "Please import valid .csv file");
            this.fileReset();
            return;
        }
    }

    var input = event.target;
    var reader = new FileReader();
    reader.readAsText(input.files[0]);

    reader.onload = (data) => {
        let csvData: any = reader.result;
        let csvRecordsArray = csvData.split(/\r\n|\n/);

        var headerLength = -1;
        if (CSVConstants.isHeaderPresentFlag) {
            let headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, CSVConstants.tokenDelimeter);
            headerLength = headersRow.length;
        }

        this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
            headerLength, CSVConstants.validateHeaderAndRecordLengthFlag, CSVConstants.tokenDelimeter);

        if (this.csvRecords == null) {
            //If control reached here it means csv file contains error, reset file.
            this.fileReset();
        }

        /* Remove the file so that user can upload same one after making changes, otherwise change event
            will not be called */
        this.clearFile();

        /* Remove the first header row */
        this.csvRecords.splice(0, 1);

        this.csvRecords.map((record: any) => {
            this.external_contacts_arr.push({
                email: record[0],
                first_name: record[1],
                last_name: record[2],
                designation: record[3],
            })
        });
        this.removeBlankRecords();
        //document.getElementById(`${this.uniquePrefix}-other-tab`).click();
    }

    reader.onerror = () => {
        this.utilService.showToastMsg("error", 'Unable to read ' + input.files[0]);
    };
}

答案 1 :(得分:0)

您可以使用以下自定义功能来完成需要的操作:

private extractData(data) { // Input csv data to the function

    let csvData = data;
    let allTextLines = csvData.split(/\r\n|\n/);
    let headers = allTextLines[0].split(',');
    let lines = [];

    for ( let i = 0; i < allTextLines.length; i++) {
        // split content based on comma
        let data = allTextLines[i].split(',');
        if (data.length == headers.length) {
            let tarr = [];
            for ( let j = 0; j < headers.length; j++) {
                tarr.push(data[j]);
            }
            lines.push(tarr);
        }
    }
    console.log(lines); //The data in the form of 2 dimensional array.
  }

您可以像这样在文件侦听器函数中读取文件:

function handleFileSelect(evt) {
      var files = evt.target.files; // FileList object
      var file = files[0];
      var reader = new FileReader();
      reader.readAsText(file);
      reader.onload = function(event){
        var csv = event.target.result; // Content of CSV file
        this.extractData(csv); //Here you can call the above function.
      }

}

在HTML内部使用以下代码:

<input type="file" (change)="handleFileSelect($event)"/>