Apurv Chaudhary
Apurv Chaudhary

Reputation: 1795

how to import CSV file in angular 4 and stored data in Database?

i want to import CSV in angular 4, and store data in my database.

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

while i click on the Submit button i want to store data in my Table.

Upvotes: 2

Views: 4899

Answers (2)

Prasan Karunarathna
Prasan Karunarathna

Reputation: 385

You can use the below custom function to do the needful :

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

You can read the file inside the file listener function like this:

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

}

Inside html use below code:

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

Upvotes: 2

Apurv Chaudhary
Apurv Chaudhary

Reputation: 1795

here is the html code.

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

below is my component code

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

Upvotes: 1

Related Questions