Управление комментариями и заметками
Введение
Комментарии используются для добавления дополнительной информации к ячейкам. Aspose.Cells предоставляет два способа добавления комментариев к ячейкам. Первый - создавать комментарии в файле дизайнера вручную. Затем эти комментарии импортируются с использованием Aspose.Cells. Второй - добавлять комментарии с использованием API Aspose.Cells во время выполнения. В этой теме будет рассмотрено добавление комментариев к ячейкам с использованием API Aspose.Cells. Также будет объяснено форматирование комментариев.
Добавление комментария
Добавьте комментарий в ячейку, вызвав метод Add коллекции Comments (инкапсулированный в объекте Worksheet). Новый объект Comment можно получить из коллекции Comments, передав индекс комментария. После получения объекта Comment настройте комментарий, используя свойство Note объекта Comment.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = ""; | |
// Create directory if it is not already present. | |
File file = new File(dataDir); | |
if(!file.exists()) | |
file.mkdir(); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Adding a new worksheet to the Workbook object | |
int sheetIndex = workbook.getWorksheets().add(); | |
// Obtaining the reference of the newly added worksheet by passing its sheet index | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
// Adding a comment to "F5" cell | |
int commentIndex = worksheet.getComments().add("F5"); | |
// Accessing the newly added comment | |
com.aspose.cells.Comment comment = worksheet.getComments().get(commentIndex); | |
// Setting the comment note | |
comment.setNote( "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-Java | |
// The path to the documents directory. | |
String dataDir = ""; | |
// Create directory if it is not already present. | |
File file = new File(dataDir); | |
if(!file.exists()) | |
file.mkdir(); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Adding a new worksheet to the Workbook object | |
int sheetIndex = workbook.getWorksheets().add(); | |
// Obtaining the reference of the newly added worksheet by passing its sheet index | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
// Adding a comment to "F5" cell | |
int commentIndex = worksheet.getComments().add("F5"); | |
// Accessing the newly added comment | |
com.aspose.cells.Comment comment = worksheet.getComments().get(commentIndex); | |
// Setting the comment note | |
comment.setNote( "Hello Aspose!"); | |
// Setting the font size of a comment to 14 | |
comment.getFont().setSize(14); | |
// Setting the font of a comment to bold | |
comment.getFont().setBold(true); | |
// Setting the height of the font to 10 | |
comment.setHeightCM(10); | |
// Setting the width of the font to 2 | |
comment.setWidthCM(2); | |
// Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls"); |
Добавить изображение в комментарий
С помощью Microsoft Excel 2007 также возможно иметь изображение в качестве фона комментария к ячейке. В Excel 2007 это можно сделать, выполнив следующие шаги. (Предполагается, что вы уже добавили комментарий к ячейке.)
- Щелкните правой кнопкой мыши ячейку, содержащую комментарий.
- Выберите Показать/скрыть комментарии и очистите любой текст из комментария.
- Щелкните по границе комментария, чтобы выбрать его.
- Выберите Формат, затем Комментарий.
- На вкладке Цвета и линии разверните список Цвет.
- Нажмите Изменение заливки.
- На вкладке Изображение нажмите Выбрать изображение.
- Найдите и выберите изображение.
- Нажмите ОК, пока все диалоговые окна не закроются.
Aspose.Cells также предоставляет эту функцию. Ниже приведен пример кода, который создает файл XLSX с нуля, добавляя комментарий в ячейку “A1” с установленным изображением в качестве его фона.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = ""; | |
// Create directory if it is not already present. | |
File file = new File(dataDir); | |
if(!file.exists()) | |
file.mkdir(); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Get a reference of comments collection with the first sheet | |
com.aspose.cells.CommentCollection comments = workbook.getWorksheets().get(0).getComments(); | |
// Add a comment to cell A1 | |
int commentIndex = comments.add(0, 0); | |
com.aspose.cells.Comment comment = comments.get(commentIndex); | |
comment.setNote("First note."); | |
comment.getFont().setName("Times New Roman"); | |
// Load an image | |
String filename = dataDir + "image.jpg"; | |
byte[] result = null; | |
java.nio.channels.FileChannel fc = null; | |
try { | |
fc = new java.io.RandomAccessFile(filename, "r").getChannel(); | |
java.nio.MappedByteBuffer byteBuffer = fc.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, 0, | |
fc.size()).load(); | |
System.out.println(byteBuffer.isLoaded()); | |
result = new byte[(int) fc.size()]; | |
if (byteBuffer.remaining() > 0) { | |
byteBuffer.get(result, 0, byteBuffer.remaining()); | |
} | |
} catch (IOException e) { | |
throw e; | |
} finally { | |
try { | |
fc.close(); | |
} catch (IOException e) { | |
throw e; | |
} | |
} | |
// Set image data to the shape associated with the comment | |
comment.getCommentShape().getFill().setImageData(result); | |
// Saving the Excel file | |
workbook.save(dataDir + "book1.out.xlsx"); |