1

I want to get the name of an existing worksheet.

Worksheet objects don’t seem to have a property for that.

I can get worksheet names from a Workbook’s Sheets property, but when handling a single worksheet, I don’t have access to its hosting Workbook.

How can I find out the name of my worksheet?

1 Answers1

1

Consider using Object.entries and pass the sheet name and data to the handling function e.g.:

const XLSX = require("xlsx");
const filename = "./Book6.xlsx";

main();

function main() {
  const workbook = XLSX.readFile(filename);
  const worksheets = workbook.Sheets;
  for (let item of Object.entries(worksheets)) {
    handleSheet({name: item[0], data: item[1]});
  }  
}

function handleSheet(ws) {
  console.log(`Name is ${ws.name}`);
  console.log(`Ref is ${ws.data["!ref"]}`);
}
Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56
  • It seems to me this is just a fancy way of passing the name along with the sheet. This doesn’t seem to meet the requirement of not having access to the workbook in the first place. – Philippe-André Lorin Jan 07 '23 at 12:48
  • To be fair - it's not that fancy... Do you want to further clarify 'not having access to the workbook' ? E.g. you mean that you have no access at all and the handling function simply recieves the workksheet object ? If so, as you already know, there is no way to get the sheet name unless you have some upstream function mutate the `Sheets` property to include the name perhaps ? – Robin Mackenzie Jan 07 '23 at 21:48
  • I was hoping I could write my code so that any function handling a worksheet would not need to be passed more than just that worksheet. I thought that if a sheet’s name was not accessible through its properties, maybe there was some other way to get it, such as a SheetJS function. Now I’m thinking that it may not make sense from SheetJS’s point of view, which may consider that a sheet’s name is relevant only in the context of a workbook. – Philippe-André Lorin Jan 08 '23 at 12:14