Управление комментариями и примечаниями
Вступление
Комментарии используются для добавления дополнительной информации к ячейкам. 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-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"); |