查找具有特定样式的单元格
Contents
[
Hide
]
有时,您需要查找具有特定样式的单元格。本文演示了如何通过使用 Microsoft Excel 和 Aspose.Cells for Java API 来实现这一点。
使用Microsoft Excel
在MS Excel中搜索具有特定样式的单元格需要以下步骤。
- 在主页选项卡中选择查找和选择。
- 选择查找。
- 如果高级选项不可见,点击选项。
- 在格式下拉菜单中选择从单元格选择格式…。
- 选择具有您想要搜索的样式的单元格。
- 点击查找全部以查找所有具有与您选择的单元格相似样式的单元格。
使用 Aspose.Cells for Java
Aspose.Cells for Java 提供了在工作表中查找具有特定样式的单元格的功能。为此,API 提供了FindOptions.setStyle()属性。
示例代码
以下代码片段可以找到所有具有与单元格A1相同样式的单元格,并更改这些单元格内的文本。请查看源文件和输出文件的截图,以分析样本代码的输出。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 = Utils.getDataDir(FindCellsWithSpecificStyle.class); | |
Workbook workbook = new Workbook(dataDir + "TestBook.xlsx"); | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Access the style of cell A1 | |
Style style = worksheet.getCells().get("A1").getStyle(); | |
// Specify the style for searching | |
FindOptions options = new FindOptions(); | |
options.setStyle(style); | |
Cell nextCell = null; | |
do { | |
// Find the cell that has a style of cell A1 | |
nextCell = worksheet.getCells().find(null, nextCell, options); | |
if (nextCell == null) | |
break; | |
// Change the text of the cell | |
nextCell.putValue("Found"); | |
} while (true); | |
workbook.save(dataDir + "out.xlsx"); |
执行代码后,所有具有与A1单元格相同样式的单元格将具有文本"已找到"。
截图
图例: 具有样式的源文件单元格
这是以下代码生成的输出文件。您可以看到所有具有与单元格A1相同样式的单元格均有文本"已找到"。
图例: 通过A1样式搜索后找到的输出文件中的单元格