我想使用office.js
删除并重新排列Word文档的各个部分。例如,Word文档有3个部分。以下是标题列表:
用户将其更改为:
最后我想看看我的Word文档中的影响。我可以轻松地向用户显示部分标题列表。用户可以更改(重新排列或删除)标题列表。我试过这样做的方法。我更改了items
的{{1}}并尝试加载sections
。这是代码:
sections
在方法参数中,function RearrangeSections(sectionHeaderList) {
Word.run(function (context) {
var sections = context.document.sections;
context.load(sections);
return context.sync()
.then(function () {
if (sections != null) {
var headers = [];
for (var i = 0; i < sections.items.length; i++) {
// Grab the header from the current section
var header = sections.items[i].getHeader('primary');
// Add loading this header to the queue
context.load(header);
// Push this header into the headers collection
headers.push(header);
}
var sectionItems = sections.items; //Get section items into a new list
context.sync().then(function () {
for (var i = 0; i < sectionHeaderList.length; i++) {
for (var j = 0; j < headers.length; j++) {
var targetHeader = sectionHeaderList[i].name; //
if (headerText == targetHeader) {
context.document.sections.items[i] = sectionItems[j]; // Change the section items
}
}
}
context.load(context.document.sections); // Finally load the sections
return context.sync().then(function () {
//
});
});
}
}).catch(function (myError) {
//otherwise we handle the exception here!
});
}).catch(errorHandler);
}
是具有更新(用户更改后)标题列表的对象列表。在这里,我只是想重新排列。
此代码不做任何事情。我是否以适当的方式尝试?
感谢阅读。欢迎任何类型的小费/帮助!
答案 0 :(得分:0)
我解决了这个问题。我选择了部分实体的Ooxml
,然后清除了文档正文并将部分实体作为我的序列。我使用了截面体的第一行来匹配这些截面。您可以使用节标题。那也行。以下是示例代码:
function RearrangeSections(sectionHeaderList) {
Word.run(function (context) {
var body = context.document.body;
var sections = context.document.sections;
context.load(body);
context.load(sections);
return context.sync()
.then(function () {
if (sections != null) {
var itemsCount = sections.items.length;
var bodies = [];
var bodiesOoxml = [];
for (var i = 0; i < sections.items.length; i++) {
var body = sections.items[i].body;
context.load(body);
bodies.push(body);
}
// Sync/Exectute the queued actions
var sectionItems = [];
sectionItems = sections.items;
context.sync().then(function () {
for (var i = 0; i < bodies.length; i++) {
var ooxml = bodies[i].getOoxml();
bodiesOoxml.push(ooxml);
}
context.sync().then(function () {
context.document.body.clear();
for (var i = 0; i < sectionHeaderList.length; i++) {
for (var j = 0; j < bodies.length; j++) {
var bodyText = bodies[j].text;
var headerText = bodyText.split("\r")[0];
var targetHeader = sectionHeaderList[i].name;
if (headerText == targetHeader) {
var val = bodiesOoxml[j].value;
body.insertOoxml(val, Word.InsertLocation.end);
}
}
}
context.load(context.document.sections);
return context.sync().then(function () {
console.log("Done");
})
});
}).catch(function (e) {
//Show error
});
}
}).catch(function (myError) {
//Show error
});
}).catch(errorHandler);
}