本文介绍如何使用 Excel JavaScript API 在工作簿中添加、更改和删除笔记。 有关备注的详细信息,请参阅 在 Excel 中插入批注和备注 一文。 有关备注和批注之间的差异的信息,请参阅 线程批注与注释之间的差异。
笔记绑定到单个单元格。 查看工作簿且具有足够权限的任何人都可以查看笔记。 工作簿中的注释由 Workbook.notes
属性跟踪。 这包括用户创建的笔记以及加载项创建的笔记。 属性 Workbook.notes
是一个 NoteCollection 对象,其中包含 Note 对象的集合。 还可以在 工作表 级别访问笔记。
提示
若要了解如何使用 Excel JavaScript API 添加和编辑注释,请参阅 使用 Excel JavaScript API 处理注释。
添加备注
NoteCollection.add
使用 方法向工作簿添加注释。 此方法采用两个参数:
-
cellAddress
:添加批注的单元格。 这可以是字符串或 Range 对象。 区域必须是单个单元格。 -
content
:注释的内容,作为字符串。
下面的代码示例演示如何向工作表中的选定单元格添加注释。
await Excel.run(async (context) => {
// This function adds a note to the selected cell.
const selectedRange = context.workbook.getSelectedRange();
// Note that an InvalidArgument error is thrown if multiple cells are selected.
context.workbook.notes.add(selectedRange, "The first note.");
await context.sync();
});
更改说明可见性
默认情况下,除非用户将鼠标悬停在带有备注的单元格上,否则便笺的内容是隐藏的,或者将工作簿设置为显示备注。 若要显示备注,请使用 Note.visible 属性。 以下代码示例演示如何更改笔记的可见性。
await Excel.run(async (context) => {
// This function sets the note on cell A1 to visible.
const sheet = context.workbook.worksheets.getActiveWorksheet();
const firstNote = sheet.notes.getItem("A1");
firstNote.load();
await context.sync();
firstNote.visible = true;
});
编辑笔记的内容
若要编辑笔记的内容,请使用 Note.content 属性。 以下示例演示如何更改 中 NoteCollection
第一个注释的内容。
await Excel.run(async (context) => {
// This function changes the content in the first note.
const sheet = context.workbook.worksheets.getActiveWorksheet();
const note = sheet.notes.getItemAt(0);
note.content = "Changing the content of the first note.";
await context.sync();
});
注意
Note.authorName
使用 属性获取笔记的作者。 作者名称是只读属性。
更改笔记的大小
默认情况下,笔记会自动调整大小以适应内容。 若要放大或缩小笔记,请使用 Note.height 和 Note.width 属性。
以下示例演示如何在 中 NoteCollection
设置第一个注释的大小。
await Excel.run(async (context) => {
// This function changes the height and width of the first note.
const sheet = context.workbook.worksheets.getActiveWorksheet();
const note = sheet.notes.getItemAt(0);
note.width = 400;
note.height = 200;
await context.sync();
});
删除笔记
若要删除笔记,请使用 Note.delete 方法。 下面的示例演示如何删除附加到单元格 A2 的笔记。
await Excel.run(async (context) => {
// This function deletes the note from cell A2.
const sheet = context.workbook.worksheets.getActiveWorksheet();
const note = sheet.notes.getItem("A2");
note.delete();
await context.sync();
});