问题
I'm writing an office-addin using the Yeoman Office generator, based on these instructions.
The default add-in has a function which will get the text selected in your word document. I'm trying to modify the function to instead get the full-text of the document.
My function code is as follows:
function getDataFromDoc(){
Office.context.document.getFileAsync(Office.CoercionType.Text,
function(result){
jQuery('#get-data-from-selection').click(getDataFromSelection);
if (result.status === Office.AsyncResultStatus.Succeeded) {
console.dir(result);
app.showNotification('The selected text is:', '"' + result.value + '"');
} else {
app.showNotification('Error:', result.error.message);
}
}
);
}
An object is returned, but when I use console.dir(result)
and look through the object I don't see the document text anywhere.
How can I modify this function so that I get back the full contents of the word document?
回答1:
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);
}
});
}
来源:https://stackoverflow.com/questions/41063377/word-add-in-get-full-document-text