Tuesday, 13 June 2017

Angular CSV import

Hi Friends,

This is my first blog and I am starting with AngularJs. I did little research on this topic as I need this in one of my projects.


For importing CSV in angular js, you first need to install bower component.

Go to your angular js setup folder and install the bower component there.

Step 1: Open Command prompt, and go to the path of your angular js folder.

Step 2: Type below command. This will install bower component "angular-csv-import".

bower install angular-csv-import

Step 3: Add js library to your application.

 <script src="bower_components/angular-csv-import/dist/angular-csv-import.js"></script>

 Step 4: Add ngCSVImport module to your application.

 angular
      .module('myApp', [
        ...
        'ngCsvImport',
        ...
      ])

 Step 5: Open the view and include the ng-csv-import element.
<ng-csv-import content="csv.content"
 material
 md-button-class="md-icon-button md-raised md-accent"
 md-svg-icon="file:ic_file_upload_24px"
 header="csv.header"
 separator="csv.separator"
 result="csv.result"
 accept="csv.accept"></ng-csv-import>



 Step 6: Open the controller and include functions related to ng-CSV-import

angular.module('myApp').
controller('MainCtrl', ['$scope', '$parse',
function ($scope, $parse) {
$scope.Math = window.Math; $scope.csv = {
content: null,
header: true,
headerVisible: true,
separator: ',',
separatorVisible: true,
result: null,
encoding: 'ISO-8859-1',
encodingVisible: true,
uploadButtonLabel: "upload a csv file",
progressCallback: function(progress) {
$scope.$apply( function() {
$scope.progress = progress;
});
}, streamingCallback: function(stream) {
if ( typeof stream != "undefined" ) {
$scope.$apply( function() {
$scope.preview = stream[Math.floor(Math.random()*stream.length)];
});
}}, streamingErrorCallback: function(streamError) {
console.log(streamError);
}};
var _lastGoodResult = '';
$scope.toPrettyJSON = function (json, tabWidth) {
var objStr = JSON.stringify(json);
var obj = null;
try {
obj = $parse(objStr)({});
} catch(e){
// eat $parse error
return _lastGoodResult;
}
var result = JSON.stringify(obj, null, Number(tabWidth));
_lastGoodResult = result;
return result;
};
}]);



 Step 7: now, if you want some changes in result, or you want a JSON object in another format or you are getting any difficulties to manage the result in your project. You can go the library which you include for ng-CSV-import and make changes as you want.

Below is the path of the library. Open this file and go to "
csvToJSON" function, and make your changes there.

<script src="bower_components/angular-csv-import/dist/angular-csv-import.js"></script>