Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
Add a sheet conditionally in Excel 2016/365 with office add-ins (Javascript API)

I'm writing a Office Add-in for Excel which needs to add a worksheet conditionally: when it's not there: add it and fill it. When it's there: fill it.

Now I do see these API's:

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

In both cases I would end-up with a sheet by the name of 'Sample'. But how do I know which to select?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The crude solution will be to try to get the sheet first and then when that fails (all async in the .sync()-call) add the sheet:

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 get, let's 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 get, let's add...");
  });
}

This could be made nicer by checking the type of error but it works.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda