Get OneDrive Item Id for Current Word doc

2019-07-17 19:04发布

问题:

I'm looking into building an add-in for Microsoft Word that would involve creating a copy of the current document.

I've found where I can copy an item through the OneDrive API. However, this requires the item-id for the document to be copied.

I can't seem to find how to get the item-id for the current Word document through the Office JavaScript API.

I've looked on the Office.context.document object, as well as the Office.context.document.getFileAsync() and Office.context.document.getFilePropertiesAysnc() functions.

How would someone get the OneDrive Item Id for the current Word doc?

回答1:

There isn't a way to do this using just Office.js, you'll need to also leverage Microsoft Graph in order to find the actual ID.

Once you have a saved file, you can get the URI using getFilePropertiesdAsync. You'll need to parse the document name and path from the URI. You can then use query filters on the Drive's Children method to isolate the specific file you're looking for.

For example, if you had a URI of https://d.docs.live.net/<id>/Documents/somedoc.docx you can determine the following:

  • This is consumer OneDrive (note the live.net URI)
  • The document name is somedoc.docx
  • It is stored in the directory Documents

To find this document you would execute the following Graph command:

https://graph.microsoft.com/v1.0/me/drive/root/children/Documents?$filter=name eq 'somedoc.docx'

All of this can be executed directly from within your add-in. Please keep in mind, users can save documents to both OneDrive and OneDrive for Business. The user must authenticate against graph using the same credentials for the drive they're saving against.



回答2:

The solution in accepted answer is not the best way to do this, maybe not anymore because microsoft changed the api since then.

It works well for root files; however, for files inside nested folders you have to execute same query multiple times until you have all the folder ids. Because you need those ids to build the full path that contains the file to search for.

Here is a simpler way to do this as of now. Suppose that get Office.context.document.getFilePropertiesAysnc() gives you https://d.docs.live.net/<id>/MyFolder1/MyFolder2/somedoc.docx.

The graph endpoint should be: https://graph.microsoft.com/v1.0/me/drive/root:/MyFolder1/MyFolder2/Document.docx