3

I am making an Angular4 I have a button that converts data to a csv file with header. Now I want to do it the other way around, I want to upload a csv file. So for testing, I make an object and make a csv file from it, and then I want to click on a button and upload that file and get the same result.

I found an angular module to export csv, but I can't find one that does it the other way around. Can someone help me with that?

This is my code:

test.ts

import { Component, OnInit} from '@angular/core';
import { Angular2Csv } from 'angular2-csv/Angular2-csv';
import {Unit} from "../../../_shared/unit";

@Component({
  moduleId: module.id,
  templateUrl: 'test.component.html',
  styleUrls: ['./test.css']
})


export class TestComponent implements OnInit {



  ngOnInit() {}

  public export() {
    // Unit (id,name,description)
    var data = [new Unit(1,"Unit1","This is unit 1!")];

    var options = {
      fieldSeparator: ';',
      quoteStrings: '"',
      decimalseparator: ',',
      showLabels: true,
      useBom: true
    };
    new Angular2Csv(data, "data", options);
  }

  public import(){}

}

test.html

<button (click)="export()">Download CSV</button>
<button (click)="import()">Upload CSV</button>
fangio
  • 1,746
  • 5
  • 28
  • 52

1 Answers1

7

You can achieve the functionality using a custom function, Try this :

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 find the detailed post here: http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html#.WWxu9XV97OQ

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 do this:

 <input type="file" (change)="handleFileSelect($event)"/>
Fahad Nisar
  • 1,723
  • 12
  • 18
  • how can I get the data, for example I need to import the file with input type="file".... – fangio Jul 17 '17 at 08:12
  • I do have an error: Property 'result' does not exist on type 'EventTarget' – fangio Jul 17 '17 at 08:45
  • can you console what you are getting in event ? – Fahad Nisar Jul 17 '17 at 08:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/149357/discussion-between-fahad-nisar-and-fangio). – Fahad Nisar Jul 17 '17 at 08:55
  • I have tested the above code and it is working fine for me.here is a working example https://embed.plnkr.co/rDa0M9QzNtDiC3IXTVwd/ – Fahad Nisar Jul 17 '17 at 10:21
  • 2
    It has to do with angular 4 and the new typescript, I had to define a new interface to make it work, https://github.com/Microsoft/TypeScript/issues/299#issuecomment-168538829 – fangio Jul 18 '17 at 07:12
  • great. Thanks for the info. – Fahad Nisar Jul 18 '17 at 07:48
  • For this.extractData to work in the callback function, you have to use [an ES6 arrow function](https://stackoverflow.com/questions/41737620/angular2-typescript-filereader-onload-property-does-not-exist). – clk Feb 13 '18 at 14:31