我使用的是 Microsoft® Word for Microsoft 365 MSO(版本 2307 内部版本 16.0.16626.20170)64 位 - 这意味着 Word API 是版本 1.5。 使用 Microsoft 教程中的 JavaScript 运行加载项示例“Office 加载项任务窗格项目”:“创建 Word 任务窗格加载项”- 页面。
这是我的“RUN”按钮单击处理程序:
export async function run() {
return Word.run(async (context) => {
/**
* Create Table
*/
const data = [
["Tokyo", "Beijing", "Seattle"],
["Apple", "Orange", "Pineapple"]
];
const table = context.document.body.insertTable(2, 3, "Start", data);
table.styleBuiltIn = Word.BuiltInStyleName.gridTable5Dark_Accent2;
table.styleFirstColumn = false;
/**
* Selecting first row and inserting ContentControl
*/
table.rows.getFirst().select("Select");
let range = context.document.getSelection();
range.insertContentControl();
/**
* At this point ContentControl covers only first row
*/
/**
* Inserting new row to the end
*/
const firstTable = context.document.body.tables.getFirst();
firstTable.addRows("End", 1, [["New", "Row", "Here"]]);
/**
* At this point ContentControl spread for all rows :(
*/
await context.sync();
});
在上面的代码中,只有第一行位于内容控件内。但是添加新行后,firstTable.addRows("End", 1, [["New", "Row", "Here"]]) 所有行都变成内容控件内。如何修复它?
在添加新行之前,您可以删除内容控件,添加一行,然后将内容控件重新添加到原始范围。
export async function run() {
return Word.run(async (context) => {
/**
* Create Table
*/
const data = [
["Tokyo", "Beijing", "Seattle"],
["Apple", "Orange", "Pineapple"]
];
const table = context.document.body.insertTable(2, 3, "Start", data);
table.styleBuiltIn = Word.BuiltInStyleName.gridTable5Dark_Accent2;
table.styleFirstColumn = false;
/**
* Selecting first row and inserting ContentControl
*/
const firstRow = table.rows.getFirst();
firstRow.load("values");
await context.sync();
const range = firstRow.getRange("Whole");
const contentControl = range.insertContentControl();
contentControl.tag = "tempTag";
await context.sync();
/**
* Remove the Content Control Temporarily
*/
const tempContentControl = context.document.contentControls.getByTag("tempTag").getFirst();
tempContentControl.delete(false); // false means the content within the control will not be deleted
await context.sync();
/**
* Inserting new row to the end
*/
const firstTable = context.document.body.tables.getFirst();
firstTable.addRows("End", 1, [["New", "Row", "Here"]]);
await context.sync();
/**
* Re-add the Content Control
*/
range.insertContentControl();
await context.sync();
});
}
tag
用于识别需要暂时删除的内容控制。添加新行后,内容控件将重新添加到原始范围。