2

I am trying to read/write data from/to local files with Microsoft Office Javascript API using Script Lab to my Excel snippet. Still did not find any proper way to do it. Have tried this solution:

function readTextFile(file) {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      if (rawFile.status === 200 || rawFile.status == 0) {
        var allText = rawFile.responseText;
        console.log(allText);
      }
    }
  };
  rawFile.send(null);
}

However when the function runs it comes up with an error like this: Network Error DOM Exception

▶["NetworkError", "https://script-lab-runner.azureedge.net/", 226, 5, DOMException]
 0: "NetworkError"

 1: "https://script-lab-runner.azureedge.net/"

 2: 226

 3: 5

 4: DOMException

Is it possible to read/write file with Microsoft Office Javascript API using Script Lab? Thanks!

mbsagin
  • 21
  • 5

2 Answers2

1

I am not sure if this helps but it seems that fetch is a better option for reading files. https://dev.to/andykao1213/how-to-read-a-local-file-with-the-browser-using-fetch-api-2cjn

Dan Miller
  • 67
  • 7
  • Thanks for answer. I ve already tried this method, but it does not work on my case. Instead of I used Office.context.document.settings to hold the data. It might help. – mbsagin Jan 20 '23 at 13:00
0

Reading a file via fetch is an option for some cases, but not for mine. Instead of I tried to use Office.Settings interface.

Office.Settings interface https://learn.microsoft.com/en-us/javascript/api/office/office.settings?view=common-js-preview

// You can set data as key-value pair. 
function setSettings(key, value) {
  Office.context.document.settings.set(key, value);
  saveSettings();
}

function saveSettings() {
  Office.context.document.settings.saveAsync(function(asyncResult) {
    if (asyncResult.status == Office.AsyncResultStatus.Failed) {
      console.log("Settings save failed. Error: " + asyncResult.error.message);
    } else {
      console.log("Settings saved.");
    }
  });
}
mbsagin
  • 21
  • 5