I want to delete and rearrange the sections of a Word document using office.js
. For example, a Word document have 3 sections. And here is the list of sections headers:
- Rocking section One
- Rocking section Two
- Rocking section Three
User changed it to:
- Rocking section Three
- Rocking section One
And finally I want to see the impact in my Word document. I can easily show user the list of headers of sections. And user can change(rearrange or delete) the list of headers. I have tried a way to do this. I changed the items
of sections
and tried to load the sections
. Here is the code:
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);
}
In the method parameter, sectionHeaderList
is a list of objects which has the updated(after user change) header list. Here I just tried to rearrange.
This code do not do any thing. Am I trying in a proper way?
Thanks for reading. Any types of tip/help is welcome !