Incorporate a new tab based on specific conditions in Excel 2016/365 using office add-ons (Javascript API)

I am currently in the process of developing an Office Add-in for Excel that requires the addition of a worksheet conditionally. I need to ensure that if the worksheet is not already present, it must be added and filled. If it already exists, I just need to fill it.

After studying the available API documentation, I have discovered these methods:

  • var sheet = context.workbook.worksheets.getItem("Sample");
  • var sheet = context.workbook.worksheets.add("Sample");

Both of these options result in a worksheet named 'Sample'. The challenge now is to determine which method to use in different scenarios.

Answer №1

In the event that the initial attempt to retrieve the sheet fails, a crude solution would be to proceed by adding the sheet asynchronously within the .sync()-call:

async function checkedAddSheet() {
  Excel.run(async (context) => {
    // For debugging:
    OfficeExtension.config.extendedErrorLogging = true;

    var sheet = context.workbook.worksheets.getItem(NEW_DATA_SHEET_NAME);
    sheet.load("name, position");

    return context.sync()
      .then(function () {
        console.log(`Found worksheet named "${sheet.name}" in position ${sheet.position}`);
      });
  }).then(function () {
    console.log("Done");
  }).catch(function (error) {
    console.error(error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
    console.log("Failed to retrieve, proceeding to add...");
    addSheet();
  });
}

function addSheet() {
  Excel.run(async (context) => {
    var sheet = context.workbook.worksheets.add(NEW_DATA_SHEET_NAME);
    sheet.load("name, position");

    return context.sync()
      .then(function () {
        console.log(`Worksheet named "${sheet.name}" was added in position ${sheet.position}`);
      });
  }).then(function () {
    console.log("Done");
  }).catch(function (error) {
    console.error(error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
    console.log("Failed to retrieve, proceeding to add...");
  });
}

Although refinement could involve error type checking, the current function serves its purpose.

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

Pass data from a JavaScript function to Objective-C in Xcode by returning an array

How can I retrieve an array of strings from Javascript in my iPhone app code? I am calling a Javascript function, and once it completes, I need to send the array of strings back to the Objective-C code. What is the best way to return the array and how can ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Finding the right property by comparing it with an array of objects in a MongoDB aggregation query

In my mongoDB collection, I have a field called 'abc' that contains an array of objects structured like this: 'abc': [{"_id": new ObjectId("someId"), "name": "entity name"}] I am looking to perfo ...

Connect or disconnect an element to a JavaScript event handler using an anonymous function

I'm stuck on a basic issue... I have a custom metabox in my WordPress blog, and here's my event handler: jQuery('tr input.test').on('click', function( event ){ event.preventDefault(); var index = jQuery(this).close ...

What is the inner workings behind server side rendering in Next.js?

I am seeking clarification on Server Side Rendering, specifically with Next.js. During server side rendering, I want to confirm the 'execution path' as follows: Client makes a request to the server for the webpage, which serves up an HTML only ...

Making sure that a commitment does not come to fruition

Perhaps this code snippet below functions correctly as it is, but I'm uncertain if it's the best approach to prevent potential runtime issues. Here's the code in question: const ep = `${environment.api.baseUrl}/login`; return this.http.pos ...

Utilizing Variables in Excel Tables with Xlsxwriter

Currently, I am using pandas concat to merge multiple dataframes into an Excel file with the help of Xlsxwriter for the output. I have a query regarding specifying the range for the table in Excel using worksheet.add_table('A1:D26'). This range ...

Removing the gridlines in a Linechart using Apexcharts

I am experiencing issues with the grid and Nodata options on my Apexchart line chart. noData: { text: none , align: 'center', verticalAlign: 'middle', offsetX: 0, offsetY: 0, style: { color: undefined, fontSize: &apo ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

The response from NodeJS is not being properly parsed by Express or BodyParser

const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const adminRoutes = require('./routes/admin'); const shopRoutes = require('./routes/shop'); // app.use(express.u ...

Tips for retrieving information from a highstock chart

Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...

The Chrome extension for the New Tab Page is taking the spotlight away from the address bar

It appears that with the latest version of Chrome, extensions that previously had the ability to override Chrome's New Tab Page and take focus away from the Omnibox no longer have this capability. Is there a different method now to give focus to an i ...

What are the best platforms for storing my pictures in the cloud?

I recently developed a website that allows users to upload images and saves them in a file. However, when I tried deploying it on Heroku, I encountered an issue where I could only upload images from my localhost and not from any other source. Additionally, ...

Converting Microsoft Word files into HTML format

Similar Question: Converting .doc to html using PHP I'm looking for a way to transform a word document into HTML format for embedding on a webpage. I'd like to accomplish this task using PHP. Any suggestions on how to achieve this? ...

Click the button to access the provided link

I need to add a link for redirection to some buttons. Here is an example of the button code: <Tooltip title="Open New Ticket"> <IconButton aria-label="filter list"> <AddTwoToneIcon /> </IconButton> </T ...

Error Loading Collada Texture: Three.js Cross Origin Issue

I'm encountering an issue with loading a Collada file using three.js that has a texture called Texture_0.png associated with it. The Collada file and the texture are stored in the same blob and accessed via a REST Web Service. CORS is enabled, allowin ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

What are the reasons for the failure of parsing this specific Twitter JSON file using Angular $http, and how can I troubleshoot and resolve the issue

After finding a JSON example on the following website (located at the bottom): , I decided to save it to a file on my local system and attempt to retrieve it using Angular's $http service as shown below: To begin, I created a service: Services.Twitt ...

Customizing the MUI X Sparkline: Incorporating the percentage symbol at the end of the tooltip data within the MUI Sparklinechart

Presented below is a SparklineChart component imported from MUI X: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-chart ...