2

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.

5
  • Have a look at this answer Commented Dec 6, 2017 at 12:00
  • i didn't get data of CSV file? @Szarik Commented Dec 6, 2017 at 12:49
  • @Chaudhary had you get the solution of your answer. Commented Nov 12, 2018 at 16:22
  • @VishwaPratap i post my answer, you can change the function as per your requirement. Commented Nov 13, 2018 at 6:28
  • @Chaudhary thanks for your response Commented Nov 13, 2018 at 10:30

2 Answers 2

2

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)"/>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.