Reading excel sheet from same workbook using nodejs - node.js

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)
*/

Related

suggest npm packages for Array to excel in Nodejs

All,
I have two simple arrays as below and want to dump the data in to excel in Nodejs. Please suggest a good npm packages for the same.
var Headers = ['ChangeId', 'ChangeDescription', 'ChangeDate', 'Enhancement/Fix', 'ExcutorTeam'];
var Data = ['INC1234', 'Multiple Cert cleanup', '04/07/2022', 'Enhancement', 'IlevelSupport'];
You can use xlsx npm package and do something like this
This is a quick example that works, things could be improved but it will at least give you a starting point
const xlsx = require('xlsx');
let Headers = ['ChangeId', 'ChangeDescription', 'ChangeDate', 'Enhancement/Fix', 'ExcutorTeam'];
let Data = ['INC1234', 'Multiple Cert cleanup', '04/07/2022', 'Enhancement', 'IlevelSupport'];
let workbook = xlsx.utils.book_new();
let worksheet = xlsx.utils.aoa_to_sheet([]);
xlsx.utils.book_append_sheet(workbook, worksheet);
xlsx.utils.sheet_add_aoa(worksheet, [Headers], { origin: 'A1' });
xlsx.utils.sheet_add_aoa(worksheet, [Data], { origin: 'A2' });
xlsx.writeFile(workbook, "Test.xlsx");
CSV format is just comma separated string with new lines. With that in mind we want to create a string that has the format:
ChangeId,ChangeDescription,ChangeDate,Enhancement/Fix,ExcutorTeam
INC1234,Multiple Cert cleanup,04/07/2022,Enhancement,IlevelSupport
We can iterate over Data in Headers.length sized chunks:
const numColumns = Headers.length;
let file = `${Headers.join(",")}\n`;
for (let i = 0; i < Data.length; i += numColumns) {
file += `${Data.slice(i, i + numColumns).join(",")}\n`;
}
fs.writeFileSync("file.csv", file);
Hope that gets you started in the right direction.

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])
}
});

Writing values into excel in Protractor

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');
});
});

how can i read data from specific row and column to specific row and column from excel sheet to json format in nodejs

I am using xlsx package. Please suggest any other package if available
I tried this but i am not getting complete data
var sheet, jsonData,
excelString = new Buffer(base64, 'base64').toString('binary'),
workbook = excelParser.read(excelString, {type: 'binary'});
if (workbook.Sheets['Sheet1']) {
sheet = workbook.Sheets['Sheet1'];
workbook.Sheets['Sheet1'] = sheet;
jsonData = excelParser.utils.sheet_to_json(workbook.Sheets['Sheet1'], {});
you can use
npm install excel
use this.
var parseXlsx = require('excel');
parseXlsx('Spreadsheet.xlsx', function(err, data) {
if(err) throw err;
// data is an array of arrays
});
and you can also visit Converting excel file to json in nodejs
Note: Make sure your Excel file is not opened by any other software (especially Excel !).
Happy coding.
var XLSX = require('xlsx');
var workbook = XLSX.readFile('Test1.xlsx');
var first_sheet_name = workbook.SheetNames[0];
// to read the value of individual cell
var address_of_cell = 'C4';
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = (desired_cell ? desired_cell.v : undefined);
console.log(desired_value);
For further clarification read through the documentation of xlsx https://www.npmjs.com/package/xlsx
var XLSX = require('xlsx');
var workbook = XLSX.readFile(path);
var sheet_name_list = workbook.SheetNames;
var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
for (let i = 0; i < xlData.length; i++) {
let employee_choice1 = xlData[i].employee_choice
var employee_choice = employee_choice1.split(',')
//implement your condition
}

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.

Resources