简体   繁体   中英

How can i make local file I/O with Microsoft Office JavaScript API using Script Lab?

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!

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

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.");
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM