Import from Excel with AngularJS - javascript

I am trying to import the Excel in to the ui-grid. I am trying to use the js xlsx library. I can convert the xlsx in to JSON but I am not sure how I can populate the xlsx in to the ui-grid. Below is the ui-grid:
$scope.samplesGridOptions = {
enableColumnResizing: true,
enableRowSelection: true,
multiSelect: false,
enableGridMenu: true,
enableCellEditOnFocus: true,
columnDefs: [
{ field: 'externalID', displayName: 'External ID' },
{ field: 'apexLotNum', displayName: 'APEX Lot' },
{
field: 'chamberName',
displayName: 'Chamber Name',
editType: 'dropdown',
editableCellTemplate: 'ui-grid/dropdownEditor',
enableCellEdit: true, editDropdownOptionsArray: $scope.chamberNameList,
editDropdownIdLabel: 'value',
editDropdownValueLabel: 'value'
}
],
gridMenuCustomItems: [],
onRegisterApi: function (gridApi) {
$scope.samplesGridAPI = gridApi;
$scope.samplesGridOptions.data = $scope.virtualSampleList;
}
};
I am trying to use the the js-xlsx library below to parse the excel file loaded. But not sure how to push that into the ui-grid, new to Javascripting and the libraries.
$scope.ParseExcelDataAndSave = function () {
var file = $scope.SelectedFileForUpload;
if (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheetName = workbook.SheetNames[0];
var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var jsonData = JSON.stringify(excelData);
if (jsonData.length > 0) {
**//Here I am not sure how can I populate the ui-grid from the JSON**
}
else {
$scope.Message = "No data found";
}
}
reader.onerror = function (ex) {
console.log(ex);
}
reader.readAsBinaryString(file);
}
}

This is the example given in the js-xlsx documentation:1
$http({
method:'GET',
url:'https://sheetjs.com/pres.xlsx',
responseType:'arraybuffer'
}).then(function(response) {
var wb = XLSX.read(response.data, {type:"array"});
var d = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
$scope.data = d;
}, function(err) { console.log(err); });
For files use:
function fileToArrayPromise(file) {
var promise = $q(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
resolve(data);
}
reader.onerror = function (ex) {
reject(ex);
}
reader.readAsArrayBuffer(file);
})
return promise;
}
fileToArrayPromise(file)
.then(function(data) {
var wb = XLSX.read(data, {type:"array"});
var d = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
$scope.data = d;
}, function(err) {
console.log(err);
throw err;
});
For more information, see
SheetJS Demos - AngularJS

Related

how to get file details of uploaded file in extJS

how to get file details of uploaded file in extJS
I am using file upload and I need to first conveert into Grid and then sumbit.
for grid conversion I have to take all files details like this :
File {
webkitRelativePath: "",
lastModifiedDate: Tue Jul 14 2009 11:02:31 GMT+0530 (India Standard Time),
name: "file.xlsx",
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
size: 780831
}
and here I am converting this to excell..
function handleFileSelect(evt){
var files = evt.target.files;
SessionConstant.uploadFileName = files[0].name;
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
// Next code
}
function ExcelToJSON () {
this.parseExcel = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
var uploadata = [];
workbook.SheetNames.forEach(function(sheetName) {
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
uploadata.push(JSON.parse(json_object));
jQuery( '#xlx_json' ).val( json_object );
});
var uploadData = uploadata;
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
so this code when I am doing by using this
{
text:'Upload',
handler : function(){
var x = document.createElement("INPUT");
x.setAttribute("type", "file");
x.setAttribute("id","upload");
document.body.appendChild(x);
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
document.getElementById('upload').click();
},
}
This is working fine.
Now If I want to implement same thing fileupload in extJS so I can submit my form :
{
xtype: 'filefield',
cls:'common-fileupload',
itemId:'fileUploadId',
clearOnSubmit:false,
width:300,
labelWidth : '0',
name: 'myFile',
buttonConfig: {
text: 'Browse',
height : 30
},
listeners: {
change: function(fld, value) {
var newValue = value.replace(/C:\\fakepath\\/g, '');
fld.setRawValue(newValue);
this.up().submit({
url: 'url',
method: 'POST',
success: function (form, action) {
},
failure: function (form, action) {
},
error: function (form, action) {
}
});
}
},
style:'margin-right:10px'
}
So In Change method How to get files details so I can write my handleFileSelect method.
Any idea willbe helpfull.
For the classic framework, following way should work:
listeners: {
change: function(fld, value) {
let file = fld.fileInputEl.dom.files[0];
}
},

DataTable to Excel Word and PDF

The code below show only 10 records because of my filters
m.getData = function (options, callback) {
table = $('#auditTrailTable').DataTable();
var info = table.page.info();
options.RecordsToSkip = info.start;
options.RecordsToTake = info.length;
var data = table.ajax.params();
options.SortDirection = data.order[0].dir;
options.ColumnName = data.columns[data.order[0].column].data;
var paramDTO = {
param: options,
searchValue: '',
dateFrom: m.filterDateFrom(),
dateTo: m.filterDateTo()
};
var url = '/AuditTrail/Find';
knock.AjaxBlockElement(paramDTO, url, '', function (result) {
if (result.Data != undefined) {
callback(result);
}
});
};
The code below is my function to export the current page shown to excel only
m.exportToExcel = function () {
var oTable = $('#auditTrailTable').DataTable();
$.fn.DataTable.Export.excel(oTable, {
filename: 'AuditTrail_Export',
title: 'WebSOA Audit Trail',
message: '',
header: ['Activity', 'Name', 'Username', 'Timestamp'],
fields: ["Activity", "Name", "Username", "TimestampString"]
});
}
;
My target is to export all records that aren't shown to excel/pdf and word but I only want to show is the current page with 10 records. Meaning all records from Page 2 up to the last page will be exported.

ionic cordova encrypt base64 image

I have this app where I take picture with cordova camera then move it into file-system , save the imgpath for the image into sqlite db and display it, I'm trying to encrypt the imgPath for the image which is saved on ccordova.file.data directory , I tried cordova safe plugin https://github.com/disusered/cordova-safe ,
but I keep getting "Error with cryptographic operation".
Any help would be appreciated
var db = null;
angular.module('starter', ['ionic', 'ngCordova']) 
.run(function($ionicPlatform, $cordovaSQLite) {    
$ionicPlatform.ready(function() {      
try {        
db = $cordovaSQLite.openDB({          
name: "my.db",
          location: 'default'        
});        
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS imageTable " + "(id integer primary key, image text)");      
} catch (e) {        
alert(e);      
} finally {       }
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller('ImageCtrl', function($scope, $rootScope, $state, $stateParams, $cordovaDevice, $cordovaFile, $ionicActionSheet, $cordovaCamera, $cordovaFile, $cordovaDevice, $ionicPopup, $cordovaActionSheet, $cordovaSQLite, $interval) {
var imagesP = [];
//$scope.images = [];
$scope.showAlert = function(title, msg) {
var alertPopup = $ionicPopup.alert({
title: title,
template: msg
});
};
$scope.loadImage = function() {
var options = {
title: 'Select Receipts Image ',
buttonLabels: ['Gallery', 'Take photo', 'File System'],
addCancelButtonWithLabel: 'Cancel',
androidEnableCancelButton: true,
};
$cordovaActionSheet.show(options).then(function(btnIndex) {
var type = null;
if (btnIndex === 1) {
type = Camera.PictureSourceType.PHOTOLIBRARY;
} else if (btnIndex === 2) {
type = Camera.PictureSourceType.CAMERA;
}
if (type !== null) {
$scope.selectPicture(type);
}
});
}
// Take image with the camera or from library and store it inside the app folder
// Image will not be saved to users Library.
$scope.selectPicture = function(sourceType) {
var options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: sourceType,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
correctOrientation: true,
targetWidth: 800,
targetHeight: 800,
popoverOptions: CameraPopoverOptions, // for IOS and IPAD
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
// Grab the file name of the photo in the temporary directory
var currentName = imagePath.replace(/^.*[\\\/]/, '');
// alert(currentName);
//Create a new name for the photo to avoid duplication
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
//alert(newFileName);
// If you are trying to load image from the gallery on Android we need special treatment!
if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) {
window.FilePath.resolveNativePath(imagePath, function(entry) {
window.resolveLocalFileSystemURL(entry, success, fail);
function fail(e) {
console.error('Error: ', e);
}
function success(fileEntry) {
var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1);
// Only copy because of access rights
$cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success) {
// $scope.image = newFileName;
var imgPath = cordova.file.dataDirectory + newFileName;
$scope.add(imgPath);
$scope.encryptFile(imgPath);
}, function(error) {
$scope.showAlert('Error', error.exception);
});
// alert( fileEntry.nativeURL);
};
});
} else {
var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
// Move the file to permanent storage
$cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success) {
// $scope.image = newFileName;
//$scope.images.push(newFileName);
var imgPath = cordova.file.dataDirectory + newFileName;
$scope.add(imgPath);
}, function(error) {
$scope.showAlert('Error', error.exception);
});
}
},
function(err) {
// Not always an error, maybe cancel was pressed...
})
};
$scope.add = function(path) {             
if (imagesP != null) {          
$cordovaSQLite.execute(db, "INSERT INTO imageTable (images) VALUES(?)", [path] );        
}        
alert("Inserted.");      
},
function(e) {        
alert(e);      
};
$scope.encryptFile = function(file){
var safe = cordova.plugins.disusered.safe,
key = 'someKeyABC';
function success(encryptedFile) {
console.log('Encrypted file: ' + encryptedFile);
}
function error() {
console.log('Error with cryptographic operation');
}
safe.encrypt(file, key, success, error);
}
  
$scope.ShowAllData = function() {     
$scope.images = [];      
$cordovaSQLite.execute(db,"SELECT images FROM imageTable").then(function(res) {          
if (res.rows.length > 0) {            
for (var i = 0; i < res.rows.length; i++) {              
$scope.images.push({                
id: res.rows.item(i).id,
image: res.rows.item(i).images
              
});            
}          
}        
},         function(error) {          
alert(error);        
}      );
 
} 
       

Mistake from cordova.js after getting file from camera

We got file, it lies in cache, and i see it in Console
But when i tried to save it and send, i got this mistakes from cordova.js
Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
Uncaught TypeError: Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
Error in Success callbackId: File1917405046 : TypeError: Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
ngCordova installed and injected
Cordova is updated
and i can't send my file, please help me
that's my code in controller
$scope.attachPhoto = function() {
$ionicActionSheet.show({
buttons: [
{ text: '<i class="icon ion-android-image"></i>Перейти в галерею' },
{ text: '<i class="icon ion-android-camera"></i> Сделать фото' }
],
cancelText: 'Cancel',
cancel: function() {
},
buttonClicked: function(index) {
var options = {
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions
};
$cordovaCamera.getPicture(options).then(function(imageData) {
onImageSuccess(imageData);
console.log(imageData);
function onImageSuccess(fileURI) {
createFileEntry(fileURI);
console.log(fileURI);
}
function createFileEntry(fileURI) {
window.resolveLocalFileSystemURL(fileURI, copyFile, fail);
console.log(fileURI);
}
function copyFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var imgBlob = new Blob([ this.result ], { type: "image/jpeg" } );
$scope.attach = true;
$scope.file = imgBlob;
};
reader.readAsArrayBuffer(file);
});
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
12345,
onCopySuccess,
fail
);
}, fail);
}
function onCopySuccess(entry) {
$scope.$apply(function () {
$scope.images.push(entry.nativeURL);
$scope.attach = true;
$scope.sendPhoto();
});
}
function fail(error) {
console.log("fail: " + error.code);
}
}, function(err) {
console.log(err);
});
console.log(options);
return true;
}
})
};
$scope.sendPhoto = function() {
var data = {
file: $scope.file
}
console.log(data);
var fd = new FormData(data);
xhr = new XMLHttpRequest();
xhr.open("POST", "http://eatmeet.ru/serv.php");
xhr.setRequestHeader('Content-Type', 'application/upload');
xhr.send(fd);
}
Try to parse a string as fileName, not a number. Please check the file documentation.
The correct syntax is:
fileEntry.copyTo(parent [DirectoryEntry], newName [DOMString], successCallback [Function], errorCallback [Function]);
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
"12345",
onCopySuccess,
fail
);
}, fail);

Cannot reload data in Fuelux Datagrid

I have tried to reload the data populated by an ajax call but I cant get it to work, it shows the old data even after using the reload method. The thing is that if I change some variables to populate a different data and try to call the following code without refreshing the page it does not reload the updated data =/ Here is my code:
function populateDataGrid() {
$.ajaxSetup({async: false});
var gridinfo="";
$.post("lib/function.php",{activity: activity, shift: shift, date: date},
function (output){
gridinfo = JSON.parse(output);
});
$.ajaxSetup({async: true});
// INITIALIZING THE DATAGRID
var dataSource = new StaticDataSource({
columns: [
{
property: 'id',
label: '#',
sortable: true
},
{
property: 'date',
label: 'date',
sortable: true
},
....
],
formatter: function (items) {
var c=1;
$.each(items, function (index, item) {
item.select = '<input type="button" id="select'+c+'" class="select btn" value="select" onclick="">';
c=c+1;
});
},
data: gridinfo,
delay:300
});
$('#grid').datagrid({
dataSource: dataSource
});
$('#grid').datagrid('reload');
$('#modal-fast-appointment-results').modal({show:true});
}
I found a solution... I had to create a new DataSource (lets call it "AjaxDataSource") and add the ajax request functionality within the data constructor:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore'], factory);
} else {
root.AjaxDataSource = factory();
}
}(this, function () {
var AjaxDataSource = function (options) {
this._formatter = options.formatter;
this._columns = options.columns;
this._delay = options.delay || 0;
this._data = options.data;
};
AjaxDataSource.prototype = {
columns: function () {
return this._columns;
},
data: function (options, callback) {
var self = this;
setTimeout(function () {
var data;
$.ajax({
url: 'getdata.php',
type: 'POST',
data: 'param1:param1,param2,param2,...,paramN:paramN', // this is optional in case you have to send some params to getdata.php
dataType: 'json',
async: false,
success: function(result) {
data = result;
},
error: function(data){
//in case we want to debug and catch any possible error
// console.log(data);
}
});
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
var match = false;
_.each(item, function (prop) {
if (_.isString(prop) || _.isFinite(prop)) {
if (prop.toString().toLowerCase().indexOf(options.search.toLowerCase()) !== -1) match = true;
}
});
return match;
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
}, this._delay)
}
};
return AjaxDataSource;
}));
After defining the new DataSource, we just need to create it and call the datagrid as usual:
function populateDataGrid(){
// INITIALIZING THE DATAGRID
var dataSource = new AjaxDataSource({
columns: [
{
property: 'id',
label: '#',
sortable: true
},
{
property: 'date',
label: 'date',
sortable: true
},
....
],
formatter: function (items) { // in case we want to add customized items, for example a button
var c=1;
$.each(items, function (index, item) {
item.select = '<input type="button" id="select'+c+'" class="select btn" value="select" onclick="">';
c=c+1;
});
},
delay:300
});
$('#grid').datagrid({
dataSource: dataSource
});
$('#grid').datagrid('reload');
$('#modal-results').modal({show:true});
}
So now we have our datagrid with data populated via ajax request with the ability to reload the data without refreshing the page.
Hope it helps someone!

Categories

Resources