JavaScript for Office Spreadsheet Titles

I'm having trouble fetching the names of sheets from an external Excel file, as I keep getting an empty array.

async function retrieveSheetNames() {
const fileInput = <HTMLInputElement>document.getElementById("file");
const fileReader = new FileReader();

fileReader.onload = (event) => {
Excel.run(async (context) => {
  // Remove the metadata before the base64-encoded string.
  const startIndex = fileReader.result.toString().indexOf("base64,");
  const workbookContent = fileReader.result.toString().substr(startIndex + 7);

  // Retrieve the workbook.
  const workbook = context.workbook;
  
  
  // Set up the options for inserting sheets.
  var options = {
    sheetNamesToInsert: [], // Insert all sheets from the workbook.
    positionType: Excel.WorksheetPositionType.after, // Insert after the `relativeTo` sheet.
    relativeTo: "Sheet1"
  }; // The sheet relative to which the other worksheets will be inserted. Used with `positionType`.

  // Insert the workbook.
  //workbook.insertWorksheetsFromBase64(workbookContent, options);
  var sheetNames = context.workbook.names;
  sheetNames.load();
  await context.sync();
  console.log(JSON.stringify(workbook.names))
  return context.sync();
  
});
};

// Read the file as a data URL to extract the base64-encoded string.
fileReader.readAsDataURL(fileInput.files[0]);
}

This code is adapted from an Office JS sample. Do you have any suggestions on how to successfully retrieve the sheet names?

Answer №1

Check out this suggested code snippet:

async function addSheets() {
  const selectedFile = <HTMLInputElement>document.getElementById("file");
  const fileReader = new FileReader();
  fileReader.onload = (event) => {
    Excel.run(async (context) => {
      // Extract the base64-encoded string by removing metadata.
      const startingPoint = fileReader.result.toString().indexOf("base64,");
      const content = fileReader.result.toString().substr(startingPoint + 7);
    
      // Access the workbook.
      const workbook = context.workbook;

      // Configure the insertion settings.
      const settings = {
        sheetNamesToInsert: [], // Insert all worksheets from the source workbook.
        positionType: Excel.WorksheetPositionType.after, // Insert after the `relativeTo` sheet.
        relativeTo: "Sheet1"
      }; // The sheet to which the other worksheets will be added. Used with `positionType`.
    
      // Insert the workbook.
      const sheetIdentifiers = workbook.insertWorksheetsFromBase64(content, settings);
      // Need to sync to load the sheetIdentifiers
      await context.sync();
      // Get references to the inserted worksheets using sheetIdentifiers
      const worksheets = sheetIdentifiers.value.map(id => context.workbook.worksheets.getItem(id));
      for (const sheet of worksheets) {
        sheet.load('name');
      }
      await context.sync();
      const sheetNames = worksheets.map(s => s.name); // array of inserted worksheet names
      console.log(sheetNames);
    });
  };
    
  // Read the file as a data URL to parse the base64-encoded string.
  fileReader.readAsDataURL(selectedFile.files[0]);
}

This code snippet will display the names of the newly inserted worksheets.

Answer №2

To retrieve a set of worksheets, you can utilize the 'items' property. After fetching the worksheets, you can loop through each item to extract the names of all the sheets and store them in an array. Refer to the sample code below:

    const workbook: Excel.Workbook = context.workbook
    const worksheets: Excel.WorksheetCollection = workbook.worksheets
    worksheets.load("items")
    await context.sync()
    let sheetItems: Excel.Worksheet[] = worksheets.items
    let sheetNames: string[] = []
    sheetItems.forEach(item => sheetNames.push(item.name))
    sheetNames.forEach(name => console.log(name))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Notification from HTML code within Django

In my Django project, I am trying to implement an alert. I am sending data from views.py to singup.html in order to display an alert based on certain conditions. However, initially the alert variable in HTML is not assigned a value. It is only after click ...

Using a data loader with react-router

I am currently working on a react app where I have implemented routes using the new data loaders from react-router-dom import { RouterProvider, createBrowserRouter, createRoutesFromElements, Route } from 'react-router-dom'; import Home fr ...

Adjust the size of a textarea once text is removed

When you type text, a textarea expands in size. But what if you want it to dynamically decrease its height when deleting text? $('textarea').on('input', function() { var scrollHeight = parseInt($(this).prop('scrollHeight&apos ...

Adjust the initial slider according to the values displayed in the following four sliders

Having an issue updating the slider value in the first one based on selected values from four other sliders. The selected value should not exceed 50, which is the maximum value in the first slider. Link to Working Fiddle : Below is the HTML code : & ...

Saving resources with a promise in Angular

I am facing a challenge while trying to handle a promise from the angular $resource save function. According to the documentation, I should be able to access the raw $http promise by using the $promise property on the returned object. Here is an example: ...

Ways to induce scrolling in an overflow-y container

Is there a way to create an offset scroll within a div that contains a list generated by ngFor? I attempted the following on the div with overflow-y: @ViewChild('list') listRef: ElementRef; Then, upon clicking, I tried implementing this with s ...

Determine the data type of a class property by referencing the data type of a different property within the

Why am I getting an error when assigning to this.propertyB in TypeScript? class Example { public readonly propertyA: boolean; private readonly propertyB: this['propertyA'] extends true ? null : 'value'; public constructor() ...

Chrome browser experiencing a disappearing vertical scroll bar issue on a Bootstrap Tab

<div class="tabs-wrap left relative nomargin" id="tabs"> <ul class="nav ultab" id="fram"> <li class="active"><a href="#history" data-toggle="tab" id="history1" >History< ...

SonarLint versus SonarTS: A Comparison of Code Quality Tools

I'm feeling pretty lost when it comes to understanding the difference between SonarLint and SonarTS. I've been using SonarLint in Visual Studio, but now my client wants me to switch to the SonarTS plugin. SonarLint is for analyzing overall pr ...

Multi-object retrieval feature in Material Dialog

I am encountering an issue with Material Dialog when confirming the action to "remove row" in a table. Initially, removing from the dialog works fine and deletes a row. However, after closing the dialog and re-calling it for the second time, the removal ac ...

A beginner's guide to crafting a knex query with MySQL language

Within MySQL Workbench, I currently have the following code: USE my_db; SELECT transactions.created_at, price FROM transactions JOIN transactions_items ON transactions.id = transactions_items.transaction_id JOIN store_items ...

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

Postponed attaching event listeners to a Vue 3 instance within an iframe

Due to a specific requirement, I find myself in need of running a Vue instance inside an iframe. After some research and adjustments based on this thread from the Vue forum, I was able to achieve this goal while adapting the code for Vue 3 and removing unn ...

How do I initiate PUT and DELETE requests from my HTML code?

I am currently in the process of developing a web application that will manage items within a list. Previously, I used buttons with event listeners and JavaScript functions to handle editing and deleting items. However, I am now transitioning towards build ...

Jerky visuals on the canvas

My canvas animation runs smoothly in Chrome, but it's as choppy as a bad haircut in Firefox. Surprisingly, the code is not even that complex. Is there anything in my code that could be causing this slowdown? Here is the jsfiddle link for reference: h ...

Activate the Air-mode feature in Summernote in addition to the standard toolbar

Is it possible to have both the default toolbar and air-mode toolbar enabled in the Summernote editor? For instance, I would like the user to utilize the default toolbar for general text editing, but have the air-mode toolbar appear when they select a spe ...

Tips for utilizing JavaScript to engage with a Cisco call manager

Our team is currently working on an IVR web application built with node js. I am wondering if it is feasible to integrate with the cisco unified call manager directly through node js in our web application? ...

Strategies for resolving type issues in NextJs with Typescript

In my project using Next.js with TypeScript, I encountered an issue while trying to utilize the skipLibCheck = false property for enhanced checking. This additional check caused the build process to break, resulting in the following error: Error info - U ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...

Issues with JQuery Ajax rendering in browser (suspected)

I'm encountering an issue on my webpage. I have a div with two hidden fields containing values of 0 and 2, respectively. Upon clicking a button that triggers an AJAX query, the div contents are updated with hidden field values of 1 and 2. However, it ...