Writing values into excel in Protractor - node.js

I am capturing some values in runtime and would like to write them back into an existing excel file.
Request your help in this aspect.
thank you

You can use npm package - xlsx. There are lot of alternative options too.
I have provided a simple example below to write the currentUrl() to an existing sheet which already contains a url
You can improvise on this to suit your needs
XLSX = require('xlsx');
describe('sample test', function(){
var workbook;
var worksheet;
beforeAll(function _setupStart() {
//Initialize workbook to read the existing excel assuming it has a sheet named 'urls'
workbook = XLSX.readFile('test.xlsx');
worksheet = workbook.Sheets['urls'];
});
it('Sample Check', function(){
browser.get("http://www.protractortest.org/#/");
browser.sleep(5000);
browser.getCurrentUrl().then(function(valueUrl){
//set the value here
worksheet['A1'].v = valueUrl
})
});
afterAll(function _finish() {
//Write the changes back
XLSX.writeFile(workbook, 'test.xlsx');
});
});

Related

Can't create xlsx files with Firebase Cloud Functions

I followed the basic usage tutorial for excel4node package.
For running the code, I have an https function which will create an Excel.xlsx file in the same directory as index.js on my local system.
The problem, however, is that every time I call the function, a zero byte Excel.xls file is created.
The function body is this:
const createXlxsFile = (req, res) => {
const xl = require('excel4node');
// Create a new instance of a Workbook class
const workbook = new xl.Workbook();
// Add Worksheets to the workbook
const worksheet = workbook.addWorksheet('Sheet 1');
const worksheet2 = workbook.addWorksheet('Sheet 2');
// Create a reusable style
const style = workbook.createStyle({
font: {
color: '#FF0800',
size: 12
},
numberFormat: '$#,##0.00; ($#,##0.00); -'
});
// Set value of cell A1 to 100 as a number type styled with paramaters of style
worksheet.cell(1, 1).number(100).style(style);
// Set value of cell B1 to 300 as a number type styled with paramaters of style
worksheet.cell(1, 2).number(200).style(style);
// Set value of cell C1 to a formula styled with paramaters of style
worksheet.cell(1, 3).formula('A1 + B1').style(style);
// Set value of cell A2 to 'string' styled with paramaters of style
worksheet.cell(2, 1).string('string').style(style);
// Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
worksheet.cell(3, 1).bool(true).style(style).style({ font: { size: 14 } });
workbook.write('Excel.xlsx');
res.end('DOC CREATED');
};
This code is working fine with standard Node.js, but not with Firebase cloud functions. Is there a restriction with writing files with the functions?
I'm having the same issue even when using the Xlsx-populate package.
OK. Figured out the issue.
The thing is that the cloud function don't allow you to write to any directory in the OS.
The only place where you have the write access to is the /tmp in the cloud functions.
On your local PC, however, this too will crash (tested in Windows 10). Probably because I had not created the C:/tmp folder.
To fix this, you can use the tmpdir() method of the os module in Node.js
const os = require('os');
const path = require('path');
const pathToSave = path.join(os.tmpdir(), 'Excel.xlsx');
While deploying the code, you will need to replace the os.tmpdir() with `/tmp'.
const pathToSave = path.join('/tmp', 'Excel.xlsx');
I hope this helps.
workbook.write('Excel.xlsx'); is asynchronous. The docs says it takes a callback which is invoked after completion. Use that to terminate the function. Right now, you're terminating early before the write can finish.
wb.write();
The write() method can accept a single filename, a
filename with callback function or an HTTP response object.
wb.write('ExcelFile.xlsx', function (err, stats) {
if (err) {
res.send(500);
} else {
res.end('DOC CREATED');
}
});
It looks like this may work as well:
wb.write('ExcelFile.xlsx', res);

Read XLSX file data with Exceljs library

Kindly see below code. I want to read data from xlsx file, worksheet name is : WPA ext libs 2017.10.05. for now I want to read values of first column. What changes should I do in code below?
please see exceljs link.
var Excel = require("exceljs");
var workbook = new Excel.Workbook();
workbook.xlsx.readFile("./CIoT_External Libraries & 3rd Party Content.xlsx")
.then(function(data){
var worksheet = workbook.getWorksheet("WPA ext libs 2017.10.05");
var lN = worksheet.getColumn(1);
console.log(lN.collapsed);
});
Yoo.. I got answer. if someone knows better answer than this please let me know. :)
var Excel = require("exceljs");
var workbook = new Excel.Workbook();
workbook.xlsx.readFile("./CIoT_External Libraries & 3rd Party Content.xlsx" )
.then(function(data){
var worksheet = workbook.getWorksheet("WPA ext libs 2017.10.05");
for(var v=1;v<=worksheet.actualRowCount;v++)
{
var lN = worksheet.getCell("B"+v).value;
console.log(" V :"+v+"------ Name :" +lN);
}
});
The best way to loop through the rows of an excel file using exceljs is using the builtin method .eachRow()
var Excel = require("exceljs");
var workbook = new Excel.Workbook();
workbook.xlsx.readFile("./CIoT_External Libraries & 3rd Party Content.xlsx" )
.then(function(data){
var worksheet = workbook.getWorksheet("WPA ext libs 2017.10.05");
worksheet.eachRow(function (row, rowNumber){
// row_values contains the values, (first column is indexed by
var row_values = row_1.values;
// Now you can access the columns directly by the column index
Console.log("Value of Column B is : "+ row_values[2])
}
});

JSON to Excel convertion in Nodejs

I'm trying to convert large amount of json data to excel and tried couple of modules
Below are my findings, if anyone used better node module which handle more data please let me know so that i can explore
json2xls
JSON array with 100000 length took 402574ms
once i exceeded to 200000 it failed with this error FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory
node-xls
JSON array with 100000 length took 444578ms
I tried this in windows 7 system with 8GB RAM, Intel Core i7, CPU # 2.10Ghz - 2.70Ghz
First push your data into a temporary array with required column and then convert it into xls, I have done it in following manner:
// use the below package to convert json to xls
var json2xls = require('json2xls');
json.forEach(function(instance, indexx,record){
var tempArry = {
'ColoumnName1' : record[indexx].columnNameVlaue,
'ColoumnName2' : record[indexx].columnNameVlaue,
'ColoumnName3' : record[indexx].columnNameVlaue,
'ColoumnName4' : record[indexx].columnNameVlaue
}
jsonArray.push(tempArry);
});
//this code is for sorting xls with required value
jsonArray.sort(function(a, b) {
return parseFloat(b.ColoumnName4) - parseFloat(a.ColoumnName4);
});
var xls = json2xls(jsonArray);
fs.writeFileSync('yourXLName.xlsx', xls, 'binary');
Dont try to add all the data into the excel file, use the specific columns you want in the file to be saved.
If its a nodejs project then do this,
const xlsx = require("xlsx")//npm install xlsx
const fs = require("fs")//npm install fs
var rawFile = fs.readFileSync("./datas.json")//dir of your json file as param
var raw = JSON.parse(rawFile)
var files = []
for (each in raw){
files.push(raw[each])
}
var obj = files.map((e) =>{
return e
})
var newWB = xlsx.book_new()
var newWS = xlsx.utils.json_to_sheet(obj)
xlsx.utils.book_append_sheet(newWB,newWS,"name")//workbook name as param
xlsx.writeFile(newWB,"Sample-Sales-Data.xlsx")//file name as param
In Ratul Das' answer, there is a typo on the following line:
var newWB = xlsx.book_new()
The code should read:
var newWB = xslx.utils.book_new()
The snippet below is the code I use to generate an Excel spreadsheet from an array of JSON objects named imageList:
const workSheet = XLSX.utils.json_to_sheet(imageList);
const workBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workBook, workSheet, "Product Image Catalog");
// Generate buffer
XLSX.write(workBook, {bookType: 'xlsx', type: 'buffer'})
// Binary String
XLSX.write(workBook, {bookType: 'xlsx', type: 'binary'})
XLSX.writeFile(workBook, 'image-catalog.xlsx')
Building the buffer helps with large amounts of data.
If your JSON is already properly formatted, you juste have to do:
const json2xls = require('json2xls');
// Example JSON
const json = [{firstName: 'Bob', name: 'Lennon'}, {firstName: 'Jack', name: 'Sparrow'}]
const xls = json2xls(json);
fs.writeFileSync('exported.xlsx', xls, 'binary');
Works fine, and very simple.

Reading excel sheet from same workbook using nodejs

I am new to nodejs, i wanted to know how it is possible to read different excel sheets from excel workbook(.xlsx) using nodejs.
I tried to use excel module of nodejs to read excel file, but using it i can only read the first sheet of that workbook. please help!!
thank you
Check this module:
https://www.npmjs.com/package/excel-multi
If you have multiple sheets in your spreadsheet,
parseXlsx('Spreadsheet.xlsx', '2', function(err, data) {
if(err) throw err;
// data is an array of arrays
});
var spread_sheet = require('spread_sheet');
var row = "1,2,Jack,Pirate";
var filePath = '/home/Pranjal/Desktop/test.xlsx';
var sheetName = "Sheet1";
var from_row = 2;
var to_row = 6;
/*
spread_sheet.addRow(row,filePath,sheetName,function(err,result){
console.log(err,result)
})
*/
/*
spread_sheet.getRows(filePath,sheetName,from_row,to_row,function(err,result){
console.log(err,result)
*/

How ensure default data in NeDB?

I'm trying to use NeDB as storage for my data in node-webkit application. I have the single collection named config.db:
var Datastore = require('nedb')
, path = require('path')
, db = new Datastore({ filename: path.join(require('nw.gui').App.dataPath, 'config.db') });
When user opens node-webkit application first time my config.db should have default data like:
{
color: "red",
font: 'bold'
...
}
Does NeDB have option for providing default data if there are no yet? Or What it the best way to save it if config.db is empty (in case if user opens node-webkit application first time)?
As far as I know NeDB does not have an option to create initial data.
I think the easiest way to achieve this is to simply query whether there is data. If counting documents returns 0, obviously the initial data have not yet been saved, so you should do this now.
If you include this check in the startup code of your application, it will automatically initialize the data on first run, and afterwards simply do nothing.
I came across this question while looking for a similar solution. I thought I'd share what I ended up with (this is a module):
var fs = require("fs");
module.exports = function (app) {
var customizationService = app.service("customization");
fs.readFile("./db/customization", "utf8", function (err, data) {
if (err) {
return console.log(err);
}
if (data) {
// Sweet, carry on
} else {
var customOptions = {
SiteTitle: "VendoMarket",
SiteTagline: "The freshest eCommerce platform around"
};
// Save data to the locations service
customizationService.create(customOptions);
}
});
};
And then in my app.js file:
//--------------------------------------
// Initialize
//--------------------------------------
var vendoInit = require("./src/init");
vendoInit(app);
(My app.js file is at the base of my project, src is a folder next to it)

Resources