File Uploader - Upload excel file and convert it into JSON and bind to the table - sapui5

After uploading the excel file on file uploader control in sapui5, excel file is converted in to JSON using following code.
handleExcelUpload : function(e) {
this._import(e.getParameter("files")
&& e.getParameter("files")[0]);
},
_import : function(file) {
if (file && window.FileReader) {
var reader = new FileReader();
that = this;
result = {};
var data;
reader.onload = function(e) {
var data = e.target.result;
var wb = XLSX.read(data, {
type : 'binary'
});
wb.SheetNames
.forEach(function(sheetName) {
var roa = XLSX.utils
.sheet_to_row_object_array(wb.Sheets[sheetName]);
if (roa.length > 0) {
result[sheetName] = roa;
}
});
};
reader.readAsBinaryString(file);
};
},
Note : I have used jszip.js and xlsx.js library to convert excel to JSON
Now in result variable I am getting JSON format data, and this data I have bind to the table.
The issue is, JSON binding with table is working fine with the Chrome, Firefox latest browser but, its not working on in IE 11 browser or it's showing only No data in table
Is there any other file reader method which supports IE11?

Yes I got answer.. I found readAsArrayBuffer method in Javascript which is compatible for all latest browser even in IE11
Here is my working code.
XML code:
<FileUploader id="fileUploader" name="myFileUpload"
class="sapUiSmallMarginEnd" uploadUrl="upload/" width="400px"
tooltip="Upload your file to the local server" uploadComplete="handleUploadComplete"
change="handleExcelUpload" placeholder="Please Select File" />
JS code:
handleExcelUpload : function(e) {
this._import(e.getParameter("files")
&& e.getParameter("files")[0]);
},
_import : function(file) {
debugger;
if (file && window.FileReader) {
var reader = new FileReader();
that = this;
//result = {};
//var data;
reader.onload = function(evt) {
var data = evt.target.result;
//var xlsx = XLSX.read(data, {type: 'binary'});
var arr = String.fromCharCode.apply(null, new Uint8Array(data));
var xlsx = XLSX.read(btoa(arr), {type: 'base64'});
result = xlsx.Strings;
result = {};
xlsx.SheetNames.forEach(function(sheetName) {
var rObjArr = XLSX.utils.sheet_to_row_object_array(xlsx.Sheets[sheetName]);
if(rObjArr.length > 0){
result[sheetName] = rObjArr;
}
});
return result;
that.b64toBlob(xlsx, "binary");
};
reader.readAsArrayBuffer(file);
};
},
b64toBlob : function(b64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
b64Data = b64Data.replace(/^[^,]+,/, '');
b64Data = b64Data.replace(/\s/g, '');
var byteCharacters = Base64.decode(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length;offset += sliceSize){
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {
type : contentType
});
}
After this add the base64 util
var Base64 = {}; // Base64 namespace
Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
Base64.encode = function(str, utf8encode) {
utf8encode = (typeof utf8encode == 'undefined') ? false : utf8encode;
var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded;
var b64 = Base64.code;
plain = utf8encode ? Utf8.encode(str) : str;
c = plain.length % 3;
if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } }
for (c=0; c<plain.length; c+=3) {
o1 = plain.charCodeAt(c);
o2 = plain.charCodeAt(c+1);
o3 = plain.charCodeAt(c+2);
bits = o1<<16 | o2<<8 | o3;
h1 = bits>>18 & 0x3f;
h2 = bits>>12 & 0x3f;
h3 = bits>>6 & 0x3f;
h4 = bits & 0x3f;
e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
}
coded = e.join('');
coded = coded.slice(0, coded.length-pad.length) + pad;
return coded;
}
Base64.decode = function(str, utf8decode) {
utf8decode = (typeof utf8decode == 'undefined') ? false : utf8decode;
var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded;
var b64 = Base64.code;
coded = utf8decode ? Utf8.decode(str) : str;
for (var c=0; c<coded.length; c+=4) {
h1 = b64.indexOf(coded.charAt(c));
h2 = b64.indexOf(coded.charAt(c+1));
h3 = b64.indexOf(coded.charAt(c+2));
h4 = b64.indexOf(coded.charAt(c+3));
bits = h1<<18 | h2<<12 | h3<<6 | h4;
o1 = bits>>>16 & 0xff;
o2 = bits>>>8 & 0xff;
o3 = bits & 0xff;
d[c/4] = String.fromCharCode(o1, o2, o3);
// check for padding
if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2);
if (h3 == 0x40) d[c/4] = String.fromCharCode(o1);
}
plain = d.join(''); // join() is far faster than repeated string concatenation in IE
return utf8decode ? Utf8.decode(plain) : plain;
}

Try this, without external library:
/*In the function "Press" */
var file = oFileUploader.getFocusDomRef().files[0];
if (file && window.FileReader) {
var reader = new FileReader();
var that = this;
reader.onload = function(e) {
var strCSV = e.target.result;
var arrCSV = strCSV.replace(/['",]/g, '').split(/[↵\n]+/).join(';').split(';');
var noOfCols = 11; // 11 Columns
var hdrRow = arrCSV.splice(0, noOfCols);
var oData = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols)
if (row.length > 1) {
for (var i = 0; i < row.length; i++) obj[hdrRow[i].replace(/\r/g, "")] = row[i].trim();
oData.push(obj) // Data Json
}
}
oTable.setModel(new sap.ui.model.json.JSONModel(oData)); // Binding model
};
reader.readAsText(file, 'ISO-8859-1');
}
Regards.

Check the code in my gist
Upload_CSV.js
Place this in the controller to parse the file using JS client side
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "ItemsJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 3;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
data.reverse();
var json = JSON.stringify(data); // send to the backend
if I did not answer you please tell me

Related

how to replace array object in flutter

if(_list.length != 0){
var shape;
var shapeCount;
var shapeCaratCount;
var shapeTotalAmount;
var details = new Map();
var temp = [Map()];
for(int l = 0 ; l <= _list.length; l++){
var list = _list[l];
if(temp.contains(list.shape)){
shapeCount += 1;
shapeCaratCount = shapeCaratCount + list.carat;
shapeTotalAmount = shapeTotalAmount + list.totalAmount;
details['Shape'] = list.shape;
details['pcs_count'] = shapeCount;
details['Carat_Count'] = shapeCaratCount;
details['total_amount'] = shapeTotalAmount;
print(details);
temp.add(details);
}else{
shapeCount = 0;
//shapeCaratCount = shapeCaratCount + list.carat;
shapeCaratCount = list.carat;
shapeTotalAmount = list.totalAmount;
details['Shape'] = list.shape;
details['pcs_count'] = shapeCount;
details['Carat_Count'] = shapeCaratCount.toString();
details['total_amount'] = shapeTotalAmount.toString();
print(details);
temp.add(details);
}
}
}
I want to replace array object of temp dictionary array.
so if any know how to do this please help i am new at flutter
this is my code please if any difficulty. please ask.

after effects - selecting render queue items via script

i'm looking for a way to select items in the render queue via script.
i'm creating a listBox that contains all the RQ items ( i need to list them in a simpler way then the RQ window, and i'm keeping the index number of each item), and i want to select from that list items and select them in the RQ.
ideas?
thanks
Dror
try{
function createUserInterface (thisObj,userInterfaceString,scriptName){
var pal = (thisObj instanceof Panel) ? thisObj : new Window("palette", scriptName,
undefined,{resizeable: true});
if (pal == null) return pal;
var UI=pal.add(userInterfaceString);
pal.layout.layout(true);
pal.layout.resize();
pal.onResizing = pal.onResize = function () {
this.layout.resize();
}
if ((pal != null) && (pal instanceof Window)) {
pal.show();
}
return UI;
};
{var res ="group {orientation:'column',\
alignment:['fill','fill'],\
alignChildren:['fill','top'],\
folderPathListbox:ListBox{\
alignment:['fill','fill'],\
properties:{\
multiline:true,\
multiselect:true,\
numberOfColumns:6,\
showHeaders:true,\
columnTitles: ['#','OM','Date','Time', 'Comp Name', 'Render Path']}\
},\
buttonGroup:Group{orientation:'row',\
alignment:['fill','bottom']\
alignChildren:['fill','bottom'],\
buttonPanel: Panel{\
text:'Actions',\
orientation: 'row',\
alignment:['fill','bottom']\
refButton: Button{text:'Refresh'}\
dupButton: Button{text:'Duplicate'}\
selButton: Button{text:'Select in RQ'}\
expButton: Button{text:'Export'}\
}\
searchPanel: Panel{\
text:'Search',\
orientation: 'row',\
searchBox: EditText{text:'search by fileName'},\
searchButton: Button{text:'Search'}, \
}\
}\
}";
}
function listRQ (rqList){
try{
var folderPathListbox = rqList;
var proj = app.project;
var totalRenderQ = proj.renderQueue.numItems;
for(var i= 1; i<=totalRenderQ; i++){
var totalOM= proj.renderQueue.item(i).numOutputModules;
for (var om= 1; om<=totalOM; om++){
var dateList, timeList, curItem;
if (proj.renderQueue.item(i).startTime != null){
var min = proj.renderQueue.item(i).startTime.getMinutes() <10 ? "0"+ proj.renderQueue.item(i).startTime.getMinutes() : proj.renderQueue.item(i).startTime.getMinutes();
var year = proj.renderQueue.item(i).startTime.getFullYear().toString().substr (-2,2);
timeList = (proj.renderQueue.item(i).startTime.getHours()-1)+":" + min;
dateList =proj.renderQueue.item(i).startTime.getDate()+"/"+(proj.renderQueue.item(i).startTime.getMonth()+1)+"/"+year ;
}else{
dateList = "not ";
timeList = "rendered";
}
curItem = folderPathListbox.add ('item', i ); // Column 1
curItem.subItems[0].text = om; // Column 2
curItem.subItems[1].text = dateList.toString(); // Column 3
curItem.subItems[2].text = timeList.toString(); // Column 4
curItem.subItems[3].text = proj.renderQueue.item(i).comp.name; // Column 5
curItem.subItems[4].text = proj.renderQueue.item(i).outputModule(om).file.toString().replace(new RegExp(",","g"), "\r").replace(new RegExp("%20","g"), " ").replace(new RegExp("%5B","g"), "[").replace(new RegExp("%5D","g"), "]"); // Column 6
}
}
}catch(err){alert(err)}
return folderPathListbox;
}
var UI = createUserInterface(this,res,"Better RQ");
var myList = UI.folderPathListbox;
var lsRq = listRQ(myList);
//~ alert(lsRq.toString());
{ // buttons action
UI.buttonGroup.buttonPanel.refButton.onClick = function () {
lsRq.removeAll();
listRQ(myList);
writeLn("all done");
}
UI.buttonGroup.buttonPanel.dupButton.onClick = function () {
var lstSlct = new Array ;
lstSlct = myList.selection;
if ( lstSlct != null){
var totalDup = lstSlct.length;
for (var i= 0; i<totalDup; i++){
var lsId = lstSlct[i].toString();
var dup = parseInt(lsId);
app.project.renderQueue.item(dup).duplicate();
writeLn("duplicated #"+dup);
}
}else{
alert ("select Something");
}
}
UI.buttonGroup.buttonPanel.selButton.onClick = function () {
app.project.renderQueue.showWindow(true) ; //shows the RQ
alert ("selButton");
}
UI.buttonGroup.buttonPanel.expButton.onClick = function () {
// var compName = myList.
alert ("expButton");
}
}
}
catch(err){
alert ("Error at line # " + err.line.toString() + "\r" + err.toString());
}

Calling a function from onEdit() trigger doesn't work

I want to run a function that updates some values when I edit one cell of a column. This line of the trigger works well: dataCell0.setValue(today_date(new Date())[2]);. But this other line updatePercent(); doesn't. But if I call this updatePercent() function from a time based trigger (in Resources), it works well. What is going wrong with this updatePercent() call?
function onEdit(){
var s = SpreadsheetApp.getActiveSheet();
if( ( s.getName() == "mySheet1" ) || (s.getName() == "mySheet2") ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( s.getRange(1, r.getColumn()).getValue() == "PORCENT_TIME") { // If you type a porcent, it adds its date.
var dataCell0 = r.offset(0, 1);
dataCell0.setValue(today_date(new Date())[2]);
updatePercent();
}
}
}
Here the updatePercent function code:
/**
* A function to update percent values accoding to input date.
**/
function updatePercent() {
var sheet = SpreadsheetApp.getActiveSheet();
var column = getColumnNrByName(sheet, "PORCENT_TIME");
var input = sheet.getRange(2, column+1, sheet.getLastRow(), 4).getValues();
var output = [];
for (var i = 0; i < input.length; i++) {
var fulfilledPercent = input[i][0];
Logger.log("fulfilledPercent = " + fulfilledPercent);
var finalDate = input[i][3];
Logger.log("finalDate = " + input[i][3]);
if ( (typeof fulfilledPercent == "number") && (finalDate instanceof Date) ) {
var inputDate = input[i][1]; // Date when input was added.
var restPorcentPen = 100 - fulfilledPercent;
var restantDays = dataDiff(inputDate, finalDate);
var percentDay = restPorcentPen/restantDays;
Logger.log("percentDay = " + percentDay);
var passedTime = dataDiff(inputDate, new Date());
Logger.log("passedTime = " + passedTime);
var passedPorcent = passedTime * percentDay; // How much percent this passed time is?
Logger.log("passedPorcent = " + passedPorcent);
var newPorcent = (fulfilledPercent + passedPorcent);
newPorcent = Math.round(newPorcent * 100) / 100;
Logger.log("newPorcent = " + newPorcent);
var newInputDate = hoje_data(new Date())[2]; // Now update the new input date
// newPorcent = newPorcent.toFixed(2);
output.push([newPorcent, newInputDate]);
sheet.getRange(2, column+1, output.length, 2).setValues(output);
Logger.log(" ");
var column25Dec = getColumnNrByName(sheet, "PORCENT_25DEZ");
var passedTimeSince25Dec = dataDiff(new Date(2013,11,25), new Date()); // Months: January is 0;
var decPercent = (newPorcent - (passedTimeSince25Dec * percentDay)); // .toFixed(2).replace(".", ",");
decPercent = Math.round(decPercent * 100) / 100;
// if (sheet.getRange(output.length+1, column25Dec+1).getValues() == ''){
sheet.getRange(output.length+1, column25Dec+1).setValue(decPercent );
// }
var remainingYears = dataDiffYears(new Date(), finalDate);
sheet.getRange(output.length+1, column).setValue(remainingYears);
}
else {
newPorcent = "Put a final date"
output.push([newPorcent, inputDate]);
sheet.getRange(2, column+1, output.length, 2).setValues(output);
}
if (finalDate instanceof Date){
var remainingYears = dataDiffYears(new Date(), finalDate);
// Logger.log("remainingYears = " + remainingYears);
}
else {
remainingYears = "insert a valid date";
}
sheet.getRange(output.length+1, column).setValue(remainingYears);
}
}
I will guess you're using the new gSheets. Check if it will work in the old-style sheets. The new sheets' onEdit trigger has problems, particularly with getActive.
My problem was in the updatePercent() funciton. Thank you, guys!

TinyMCE strip_tags function like php?

how can I accept just certain tags and strip_tags all others when paste text to editor? just like php's strip_tags function?
and how can I remove all styles from that tags?
input is a string.
i have a function to this
var strip_tags = function(str,tags,attrs){
var reg2 = /\s*(\w+)=\"[^\"]+\"/gm;
var reg = /<\s*(\w+).*?>/gm;
str = str.replace(reg,function(match, i) {
var r_ = match;
var reg_ = /<\s*(\w+).*?>/gm;
var m_ = reg_.exec(match);
if(m_!=null){
if(tags.indexOf(m_[1])>=0){
r_ = match.replace(reg2,function(match_, i) {
var reg2_ = /\s*(\w+)=\"[^\"]+\"/gm;
var m = reg2_.exec(match_);
if(m!=null){
if(attrs.indexOf(m[1])>=0){
return match_;
}
}
return '';
});
}else{
r_ = '';
}
}else{
r_ = '';
}
return r_;
});
var reg3 = /<\/\s*(\w+).*?>/gm;
str = str.replace(reg3,function(match, i) {
var r_ = match;
var reg_ = /<\/\s*(\w+).*?>/gm;
var m_ = reg_.exec(match);
if(m_!=null){
if(tags.indexOf(m_[1])>=0){
return match;
}
}
return '';
});
return str;
};
tinyMCE.init(
...
plugins: "paste...
paste_preprocess : function(pl, o) {
var allowed_tags = ['ul','li','b','p','table','tr','td'];
var allowed_attributes = ['href','colspan','rowspan'];
o.content = strip_tags(o.content,allowed_tags,allowed_attributes);
},
...
);

I'm trying to re-write this in CoffeeScript. Coming unstuck

function getElementsByClassName(className)
{
// get all elements in the document
if (document.all)
{
var allElements = document.all;
}
else
{
var allElements = document.getElementsByTagName("*");
}
var foundElements = [];
for (var i = 0, ii = allElements.length; i < ii; i++)
{
if (allElements[i].className == className)
{
foundElements[foundElements.length] = allElements[i];
}
}
return foundElements;
}
var listItems = document.getElementsByClassName("quirky");
for (var i = 0, ii = listItems.length; i < ii; i++)
{
alert(listItems[i].nodeName);
}
getElementsByClassName = (className) ->
# get all elements in the document
if document.all
allElements = document.all
else
allElements = document.getElementsByTagName "*"
el for el in allElements when el.className == className
# NOTE: getElementsByClassName was never assigned as a member
# of document. So this call will likely fail, unless you are
# using a latest-version browser.
listItems = document.getElementsByClassName "quirky"
for i in listItems
alert i.nodeName