I need to separate all the headers of Excel sheet. code that i implemented is working but only text format is working. kindly help.
const xlsx = require('xlsx');
const workbook = xlsx.readFile('./SMALL.xlsx');
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const workbookHeaders = xlsx.readFile('./SMALL.xlsx', { sheetRows: 1 });
const columnsArray = xlsx.utils.sheet_to_json(workbookHeaders.Sheets[workbook.SheetNames[0]], { header: 1 })[0];
console.log(columnsArray);
Response
My console should print ['Task', '1/2022', '2/2022' ]. instead its printing
[ 'Task', 44562, 44593 ]
Looks like you can specify a date format string in the options parameter to the sheet_to_json(worksheet, opts) method.
The option property name appears to be: dateNF
https://www.npmjs.com/package/xlsx#parsing-options
I have to put file sizes(need to capture from UI) near to file name(contained in excel) but was finding it difficult to insert such entry and so I created another sheet and class named FileProperties with filePath and fileSize. Then I had put the entries as JSON into new worksheet, then I want to delete the old sheet containing just the file names and want to rename the existing sheet so that it appears same. But when I used rename() and delete() on worksheet level I got an error and the work is more tedious then if I can write the file sizes near to file name in the old sheet.
FileProperties class
export class FileProperties {
filePath;
fileSize;
}
Below are the initialization and initially InputSheet is empty and Input_Data is holding File paths under File Path heading
inputWorksheet = workbook.Sheets.InputSheet;
oldInputSheet = workbook.Sheets.Input_Data;
const temp = XLSXReader.utils.sheet_to_json(oldInputSheet);
temp.forEach((res) => {
data.push(res);
});
Below is the code which I was trying to get the entries in new sheet which worked successfully.
allDataEle = await page.waitForSelector (
"locator passed here"
);
fileSize = await page.evaluate((el) => el.textContent.trim(), allDataEle);
//data is an object which refers to row of old sheet
fileProperties.filePath = data[i]['File Path'];
fileProperties.fileSize = fileSize;
fileProp = [fileProperties];
cell = 'A' + (i+2);
//inputWorksheet is referring to new sheet name
XLSXReader.utils.sheet_add_json(inputWorksheet, fileProp, {
skipHeader: true,
origin: cell
});
XLSXReader.writeFile(workbook, excelSheetName.xlsx');
I am getting proper data but want to write the file sizes in the old sheet and not getting another sheet for this.
I used the xlsx module in a node electron project to extract the content of an excel file
I am only able to extract the items in the first column successfully
But I am unable to extract the content of subsequent columns
Please advise me on how I can get the content of subsequent columns.
var XLSX = require("xlsx");
var workbook = XLSX.readFile(excelFile.path);
var sheet_name_list = workbook.SheetNames;//gives sheet name
var worksheet = workbook.Sheets[sheet_name_list];
var dataArray = XLSX.utils.sheet_to_json(worksheet);
alert("dataArray is : " + dataArray);
[![enter image description here][1]][1]
var newData = dataArray.map(function (record) {
alert("rec 1 :" + record[1])
alert("rec 2 :" + record[2])
I attached screenshots of the alert pop-ups generated by javascript 1]1 2]2 and also a screenshot of the xlsx 3 file being uploaded and extracted
You can see from the screenshot that I extracted the content of the first column using record1 which comes as 1
But the content of other columns come as undefined
Why do other columns come as undefined and how do I get the content of other columns
I was able to iterate using below code
const workbook = XLSX.readFile(excelFile.path);
var sheetNames = workbook.SheetNames;
// alert("sheetnames :> " + sheetNames);
var sheetIndex = 1;
var df = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[sheetIndex-1]]);
// alert(JSON.stringify(df));
// alert(JSON.stringify(df, null, 4));
// alert("df Length :> " + df.length);
df.forEach(function (arrayItem) {
var x = arrayItem;
alert(JSON.stringify(x.ID));
// alert(JSON.stringify(x, null, 4));
});
I wrote a JS code where I imported SheetJS and js-xlsx to perform actions on XLSX files (I can't use nodeJs nor npm, bower or any other solution that requires any installation on final user computer).
Shortly, the code has to do the following:
gets data that will be added to excel from user;
imports the excel the user wants to edit;
use a function to determine in which row data has to be added;
save and download a new file with updated data
The problem with the code I wrote is that it works just fine with Excels written, in fact, via Excel, but crashes if a user imports an XLSX that was previously generated and downloaded by my code.
Here's a snippet of the code:
// user choose the source excel
$('#xlf').change(function(e) {
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function(e) {
var data = new Uint8Array(reader.result);
var wb = XLSX.read(data, {
type: 'array',
cellDates: true,
cellStyles: true,
sheetStubs: true,
raw: true
});
var fSN = wb.SheetNames[0];
var ws = wb.Sheets[fSN];
function findEmpty() {
// this function check all the values in a specific range of cells (C9:C25)
// In order to do so, I included them into an array where I stored the value of the cells;
// later I loop the array and add 1 to the counter *dataSize* anytime I found a value > 0
var dataRange = [ws["C9"].v, ws["C10"].v, ws["C11"].v, , ws["C12"].v, ws["C13"].v, ws["C14"].v, ws["C15"].v, ws["C16"].v, ws["C17"].v, ws["C18"].v, ws["C19"].v, ws["C20"].v, ws["C21"].v, ws["C22"].v, ws["C23"].v, ws["C24"].v, ws["C25"].v];
var dataSize = 0;
var row;
for (i = 0; i < dataRange.length; i++) {
if (dataRange[i] > 0)
dataSize++;
}
row = 8 + dataSize; // 8 is the row of C9 (0 index-based)
return row;
}
var firstEmpty = findEmpty();
var header = ["a", "b", "c", "d", "e", "f"];
//origin is firstEmpty
XLSX.utils.sheet_add_json(ws, [{
a: $('#from').val(),
b: $('#to').val(),
c: $("#differenza").val(),
e: $("#comm").val()
}], {
header: header,
origin: firstEmpty,
skipHeader: true
});
// save file
XLSX.writeFile(wb, "test.xlsx");
}
});
If I try storing in dataRange the cells without the value (.v):
var dataRange = [ws["C9"], ws["C10"], ws["C11"], ws["C12"], ws["C13"], ws["C14"], ws["C15"], ws["C16"], ws["C17"], ws["C18"], ws["C19"], ws["C20"], ws["C21"], ws["C22"], ws["C23"], ws["C24"], ws["C25"]];
it won't crash with neither Excel generated files nor this-code-generated files, however the function findEmpty() will not work as intended (dataSize will be 0, no matter what's inside the cells).
Looks like my code can't write proper cell objects.
My guess is that there's something I should fix with the way I'm saving the file, but after several research and attempts I couldn't figure out a way to fix this - do you have a clue?
Thanks to all
Just in case this could help anyone, I solved my problem changing the IF condition within the FOR loop like this:
if((dataRange[i] !== undefined) && (dataRange[i].v > 0))
dataSize++;
Also, I'm using the dataRange array where I did not pass the .v property
(dataRange = [ws["C9"], ws["C10"], ... , ...])
After few attempts I found my code was not able to read within the .v of a cell of a file it generates, still it write and passes the whole cell object to it
1 -I want to add a new record inside the excel which is already contains some value
2 - Is there any way to use excel as the database for our project
so that client can use the excel effieciently
//script file.js
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
//calling 2 function (writeFile() and writeFile1() )
writeFile();
writeFile1();
// this function should add/ create the record in excel file
function writeFile(){
var worksheet = workbook.addWorksheet('sheet1');
worksheet.columns =[
{header:"Id",key:"id",width:10},
{header:'Type',key:'type',width:15},
{header:'Assigned Engineer',key:'eng',width:25},
{header:'Due Date',key:'ddate',width:18},
{header:'Client Name',key:'cname',width:20},
{header:'person Name',key:'pname',width:20},
{header:'enquiry type',key:'etype',width:18},
{header:'acknowledge',key:'ack',width:20}
]
Worksheet.addRow({id:16,type:"Trading1221",eng:"Dhanasekar122",ddate:new
Date(),cname:"Ford22",pname:"sekar22",etype:"pipeling2",ack:"Y2"})
worksheet.addRow({id:71,type:"Trading3221",eng:"Dhanasekar322",ddate:new
Date(),cname:"Ford32",pname:"sekar32",etype:"pipeling3",ack:"Y3"})
workbook.xlsx.writeFile('file2.xlsx').then(function(){
})
}
//similary this below function should also add the record inside the
// excel
function writeFile1(){
var worksheet = workbook.addWorksheet('sheet1');
worksheet.columns =[
{header:"Id",key:"id",width:10},
{header:'Type',key:'type',width:15},
{header:'Assigned Engineer',key:'eng',width:25},
{header:'Due Date',key:'ddate',width:18},
{header:'Client Name',key:'cname',width:20},
{header:'person Name',key:'pname',width:20},
{header:'enquiry type',key:'etype',width:18},
{header:'acknowledge',key:'ack',width:20}
]
Worksheet.addRow({id:11,type:"Trading1221",eng:"Dhana11sekar122",ddate:new
Date(),cname:"Fo12",pname:"sekar122",etype:"pi1peling2",ack:"Y2"})
worksheet.addRow({id:171,type:"Trading31221",eng:"Dhanasekar11322",ddate:new
Date(),cname:"For1d32",pname:"sek1ar32",etype:"pipelin1g3",ack:"Y13"})
workbook.xlsx.writeFile('file2.xlsx').then(function(){
})
}
// what happening is value is overwriting and the excel has the last
inserted value
I had even tried in the second function of removing the columns but
still works the same and shows error on some time
excelJS requires an array of objects where each object points to row in excel , try doing this , this should solve your pblm
var rows = [{id:11,type:"Trading1221",eng:"Dhana11sekar122",ddate:new Date(),cname:"Fo12",pname:"sekar122",etype:"pi1peling2",ack:"Y2"},
{id:171,type:"Trading31221",eng:"Dhanasekar11322",ddate:new Date(),cname:"For1d32",pname:"sek1ar32",etype:"pipelin1g3",ack:"Y13"}];
worksheet.addRows(rows);
At last i found the solution to the above problem
//file1.js
var Excel = require('exceljs')
var workbook = new Excel.Workbook()
var arr=[]
workbook.xlsx.readFile('./file4.xlsx')
.then(function(){
var worksheet = workbook.getWorksheet(1)
var row =[
[ 55,"trading","sekar",new Date(2017-02-12),"ashok leyaland",arun",
"modeling","Y"],
[99,"training",new Date(2018-02-13),"tata motors","dhana","reference
name","wheldding","Y"]
]
worksheet.addRows(row)
return workbook.xlsx.writeFile('./file4.xlsx')
})
//
first you need to read the respective excel file and then you need to select the particular worksheet of the workbook(excel file) now you can readfile are write file using any of the form you can choose and update the value of the excel in the form of array or arrays
and return the output as file write function