我使用的是 Microsoft® Word for Microsoft 365 MSO(版本 2307 内部版本 16.0.16626.20170)64 位 - 这意味着 Word API 是 version 1.5 。 使用 Microsoft 教程中的 JavaScript 运行加载项示例“Office 加载项任务 Pane 项目”:“创建 Word 任务 Pane 加载项”- page 。
这是我的“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();
});
}
标签
用于标识需要暂时删除的内容控件。添加新行后,内容控件将重新添加到原始范围。
关于javascript - Office.js : ContentControl in table broken after inserting row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76973084/