Office-js Excel: Get filename of newly saved file
Asked Answered
C

2

5

How can I get filename of newly saved file? Normally, I can get the filename using:

Office.context.document.url

However, when the user opens a new workbook, it doesn't really have a filename, and oddly enough this line of code doesn't work even after they save it. Instead, they have to save it, close, and then re-open the file for that code to read their filename.

Is there a way to refresh the Office context after a save, or another workaround for this?

Crellen answered 28/6, 2018 at 22:35 Comment(1)
Have you tried Office.context.document.getFilePropertiesAsync([, options], callback);. From the documentation I can gather that this should also return the document url.Rhigolene
B
3

We can get the file path for the given document. getFilePropertiesAsync(options, callback)

var fileProperties = Office.context.document.getFilePropertiesAsync([, options], callback);
var fileUrl = fileProperties.url;
  • If you opened from a document library, you'll get the full URL of the document including the file name.
  • If you opened the file from your local drive it will give you the full path of the document (including the file name as well)
  • If the file has not yet been saved, it will return null.
Botryoidal answered 10/4, 2019 at 16:2 Comment(0)
C
3

Thanks @Nate Radebaugh for pointing out: getFilePropertiesAsync(options, callback) That works as expected and is able to provide the filename of a newly saved document.

Since I'm a bigger fan of async/await over callbacks, I thought I'd add this to his answer:

async loadFileName() {
  return new Promise((resolve) => {
    Office.context.document.getFilePropertiesAsync(null, (res) => {
      if (res && res.value && res.value.url) {
        let name = res.value.url.substr(res.value.url.lastIndexOf('\\') + 1);
        resolve(name);
      }
      resolve('');
    })
  });
}

res.value.url returns the entire file url/path (C:\Users\username\Desktop\Book1.xlsx) and in my case, since I only want the filename (Book1.xlsx), I trim it off the end.

Crellen answered 14/6, 2019 at 22:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.