Word Add-in Get full Document text?

时光总嘲笑我的痴心妄想 提交于 2019-12-06 20:54:28
Juan Balmori

If you used the Word specific APIs for this, your code could be simplified to:

Word.run(function(context) {
    // Insert your code here. For example:
    var documentBody = context.document.body;
    context.load(documentBody);
    return context.sync()
    .then(function(){
        console.log(documentBody.text);
    })
});

I think that's more convenient. At any rate the getFileAsync method just gives you a handler for the file, then you need to slice it to get the content. Check out this example:

function getFile(){
        Office.context.document.getFileAsync(Office.FileType.Text, { sliceSize: 4194304  /*64 KB*/ },
          function (result) {
              if (result.status == "succeeded") {
                  // If the getFileAsync call succeeded, then
                  // result.value will return a valid File Object.
                  var myFile = result.value;
                  var sliceCount = myFile.sliceCount;
                  var slicesReceived = 0, gotAllSlices = true, docdataSlices = [];
                  app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);

                  // Get the file slices.
                  getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
              }
              else {
                  app.showNotification("Error:", result.error.message);
              }
          });
    }


    function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived) {
        file.getSliceAsync(nextSlice, function (sliceResult) {
            if (sliceResult.status == "succeeded") {
                if (!gotAllSlices) { // Failed to get all slices, no need to continue.
                    return;
                }

                // Got one slice, store it in a temporary array.
                // (Or you can do something else, such as
                // send it to a third-party server.)
                docdataSlices[sliceResult.value.index] = sliceResult.value.data;
                if (++slicesReceived == sliceCount) {
                    // All slices have been received.
                    file.closeAsync();
                    console.log(docdataSlices); // docDataSlices contains all the text....
                }
                else {
                    getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
                }
            }
            else {
                gotAllSlices = false;
                file.closeAsync();
                app.showNotification("getSliceAsync Error:", sliceResult.error.message);
            }
        });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!