Управление комментариями и примечаниями

Вступление

Комментарии используются для добавления дополнительной информации к ячейкам. Aspose.Cells предоставляет два метода добавления комментариев к ячейкам. Первый заключается в создании комментариев в файле конструктора вручную. Затем эти комментарии импортируются с использованием Aspose.Cells. Второй способ — добавить комментарии с использованием Aspose.Cells API во время выполнения. В этом разделе обсуждается добавление комментариев к ячейкам с помощью Aspose.Cells API. Также будет объяснено форматирование комментариев.

Добавление комментария

Добавьте комментарий к ячейке, вызвав методКомментарии коллекцияДобавлять метод (инкапсулированный вРабочий лист объект). НовыйКомментарий доступ к объекту возможен изКомментарии коллекции, передав индекс комментария. После доступа кКомментарий объект, настройте примечание комментария с помощьюКомментарий объектыЗаписьимущество.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Adding a new worksheet to the Workbook object
int sheetIndex = workbook.Worksheets.Add();
// Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[sheetIndex];
// Adding a comment to "F5" cell
int commentIndex = worksheet.Comments.Add("F5");
// Accessing the newly added comment
Comment comment = worksheet.Comments[commentIndex];
// Setting the comment note
comment.Note = "Hello Aspose!";
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Форматирование комментариев

Также возможно отформатировать внешний вид комментариев, настроив их высоту, ширину и параметры шрифта.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Adding a new worksheet to the Workbook object
int sheetIndex = workbook.Worksheets.Add();
// Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[sheetIndex];
// Adding a comment to "F5" cell
int commentIndex = worksheet.Comments.Add("F5");
// Accessing the newly added comment
Comment comment = worksheet.Comments[commentIndex];
// Setting the comment note
comment.Note = "Hello Aspose!";
// Setting the font size of a comment to 14
comment.Font.Size = 14;
// Setting the font of a comment to bold
comment.Font.IsBold = true;
// Setting the height of the font to 10
comment.HeightCM = 10;
// Setting the width of the font to 2
comment.WidthCM = 2;
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Добавить изображение в комментарий

В Microsoft Excel 2007 также можно использовать изображение в качестве фона для комментария к ячейке. В Excel 2007 это достигается выполнением следующих шагов. (Они предполагают, что вы уже добавили комментарий к ячейке.)

  1. Щелкните правой кнопкой мыши ячейку, содержащую комментарий.
  2. ВыбиратьПоказать/скрыть комментариии удалите любой текст из комментария.
  3. Нажмите на границу комментария, чтобы выделить его.
  4. ВыбиратьФормат , тогдаКомментарий.
  5. НаЦвета и линии вкладку, развернитеЦвет список.
  6. НажмитеЭффекты заливки.
  7. НаРисунок вкладка, нажмитеВыберите изображение.
  8. Найдите и выберите изображение.
  9. НажмитеХОРОШО пока не закроются все диалоги.

Aspose.Cells также предоставляет эту функцию. Ниже приведен пример кода, который создает файл XLSX с нуля, добавляя комментарий к ячейке «A1» с изображением в качестве фона.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiate a Workbook
Workbook workbook = new Workbook();
// Get a reference of comments collection with the first sheet
CommentCollection comments = workbook.Worksheets[0].Comments;
// Add a comment to cell A1
int commentIndex = comments.Add(0, 0);
Comment comment = comments[commentIndex];
comment.Note = "First note.";
comment.Font.Name = "Times New Roman";
// Load an image into stream
Bitmap bmp = new Bitmap(dataDir + "logo.jpg");
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
// Set image data to the shape associated with the comment
comment.CommentShape.Fill.ImageData = ms.ToArray();
// Save the workbook
workbook.Save(dataDir + "book1.out.xlsx", Aspose.Cells.SaveFormat.Xlsx);

Предварительные темы