Skip to content

Template: defined names

A name is { Name, Ref, Sheet? }. Sheet is the zero-based sheet for a name that belongs to one sheet. Leave it out for a global name.

  • template_book_add_name(wb, name) adds a name. It updates the name when the template has it already.
  • template_book_set_name(wb, name) changes the Ref of an existing name. Ref must be a string such as "Sheet1!$A$1:$A$2" or "3". With Sheet, it changes only the name with that scope. Without it, it changes only the global name.
  • template_book_remove_name(wb, spec) removes names. With Sheet, it removes only that scope. Without it, it removes only the global name. With Sheet: -1, it removes every name called Name. Formulas that use the removed name are not rewritten.
const XLSX = require("@agent-sheet/wasm");
const src = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(src, XLSX.utils.aoa_to_sheet([[1, 2], [3, 4]]), "Sheet1");
XLSX.utils.book_append_sheet(src, XLSX.utils.aoa_to_sheet([[5]]), "Sheet2");
src.Workbook = { Names: [
{ Name: "Global", Ref: "Sheet1!$A$1:$A$2" },
{ Name: "Local", Sheet: 0, Ref: "Sheet1!$B$1:$B$2" },
{ Name: "Local", Sheet: 1, Ref: "Sheet1!$C$1:$C$2" },
] };
const wb = XLSX.read(XLSX.write(src, { type: "buffer", bookType: "xlsx" }), { template: true });
const names = () => XLSX.read(XLSX.write(wb, { type: "buffer", bookType: "xlsx", template: true })).Workbook.Names.map((n) => n.Name + "@" + n.Sheet + "=" + n.Ref);
XLSX.utils.template_book_add_name(wb, { Name: "New", Ref: "Sheet1!$A$1" });
XLSX.utils.template_book_set_name(wb, { Name: "Global", Ref: "3" });
XLSX.utils.template_book_set_name(wb, { Name: "Local", Sheet: 1, Ref: "4" });
console.log(names());
XLSX.utils.template_book_remove_name(wb, { Name: "Local", Sheet: -1 });
console.log(names());
Output
[
'Global@undefined=3',
'Local@0=Sheet1!$B$1:$B$2',
'Local@1=4',
'New@undefined=Sheet1!$A$1'
]
[ 'Global@undefined=3', 'New@undefined=Sheet1!$A$1' ]

The original documentation calls the removal function template_book_delete_name. That name does not exist. Use template_book_remove_name.