问题
I am writing an office add-in with angularjs, i need to get and set document title (that seen at that the top of the document).
this is my code:
function run() {
Word.run(function (context) {
var properties = context.document.properties;
context.load(properties);
return context.sync()
.then(function() {
console.log('thisDocument.properties.title', properties.title);
})
})
.catch(function(error) {
OfficeHelpers.UI.notify(error);
OfficeHelpers.Utilities.log(error);
});
}
but in console didn't print the title of document!
回答1:
The context.document.properties.title property that you're writing to the console is the file-level attribute Title that is displayed under Properties if you select File >> Info (in Excel running on Windows Desktop). It is not the "title" (text) that you see at that the top of your document, or the name of the file itself. I'd suspect that if you examine the file-level attribute Title for your document (via the Word UI), you'll see that the Title attribute is not populated -- it won't be populated unless you've explicitly set it.
I'm not super-familiar with the Word API object model, but here's something that might be helpful. The following code snippet gets the first paragraph of the document (which, if the first line of a document is the title, will represent the title of the document), and then updates the text of the title with a new text string (while maintaining any previous formatting, etc.).
Word.run(function (context) {
// get the first paragraph
// (if the first line of the document is the title, this will be the contents of the first line (title))
var firstParagraph = context.document.body.paragraphs.getFirst();
firstParagraph.load("text");
// get the OOXML representation of the first paragraph
var ooXML = firstParagraph.getOoxml();
return context.sync()
.then(function () {
// replace the text of the first paragraph with a new text string
firstParagraph.insertOoxml(ooXML.value.replace(firstParagraph.text, "NEW TITLE"), "Replace");
return context.sync();
});
}).catch(function (error) {
console.log("Error: " + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
Note: If you cannot assume that the first paragraph of the document will always be the document title (i.e., if sometimes the document may not have a title, or if sometimes the title may be preceded by one or more blank lines, for example), you'll need to add additional logic to the snippet above to determine whether or not the first paragraph of the document is indeed a title, before proceeding with the logic that replaces the contents of the first paragraph.
来源:https://stackoverflow.com/questions/46288851/how-can-i-get-the-document-title-in-office-365-javascript-api