我正在使用 Yeoman Office generator 编写一个办公插件, 基于 these instructions .
默认的加载项有一个函数,可以获取在您的 word 文档中选择的文本。我正在尝试修改函数以获取文档的全文。
我的函数代码如下:
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);
}
}
);
}
返回了一个对象,但是当我使用 console.dir(result)
并查看该对象时,我在任何地方都看不到文档文本。
如何修改这个函数,才能取回word文档的全部内容?
最佳答案
如果您为此使用了 Word 特定的 API,您的代码可以简化为:
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);
})
});
我觉得这样更方便。无论如何,getFileAsync 方法只是为您提供文件的处理程序,然后您需要对其进行切片以获取内容。看看这个例子:
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);
}
});
}
关于javascript - Word 加载项获取完整的文档文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41063377/