CSV file contains Comma separated values, records are distinguished by new line. By using split function we can get records easily.

Program Flow

  1. Get CSV file content using HTTP request
  2. Process CSV file data
  3. Format JavaScript object and display it in a table

Markup to display CSV content in Table

<table>
    <tr ng-repeat="x in data">
      <td ng-repeat="y in x">{{ y }}</td>
    </tr>
</table>

Script

$scope.processData = function(allText) {
    // split content based on new line
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');
    var lines = [];

    for ( var i = 0; i < allTextLines.length; i++) {
        // split content based on comma
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {
            var tarr = [];
            for ( var j = 0; j < headers.length; j++) {
                tarr.push(data[j]);
            }
            lines.push(tarr);
        }
    }
    $scope.data = lines;
};

3 comments:

  1. how to display in html table using input type file

    ReplyDelete
  2. thanks this is very helpfull but this is not working csv file which contain two blank colom like "","" can u pls help me

    ReplyDelete
  3. Hi and thanks for the article, but if still will the same problem, you should be looking for another file, you can use a open .csv file https://wikiext.com/csv and easy fix the problem, maybe it's just because that initially you have the wrong file. Any way, try to do this somehow.

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts