搜索和替换范围内的数据
Contents
[
Hide
]
有时,您需要搜索和替换范围内的特定数据,忽略所需范围之外的任何单元格值。 Aspose.Cells 允许您将搜索限制在特定范围内。这篇文章解释了如何。
Aspose.Cells 提供了FindOptions.setRange() 搜索数据时指定范围的方法。
假设你想搜索字符串**“搜索”**并将其替换为**“代替”**范围中**E3:H6**.在下面的屏幕截图中,可以在多个单元格中看到字符串“search”,但我们只想在给定范围内替换它,此处以黄色突出显示。
输入文件
代码执行后,输出文件如下所示。范围内的所有“搜索”字符串都已替换为“替换”。
输出文件
This file contains hidden or 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(SearchReplaceDataInRange.class); | |
Workbook workbook = new Workbook(dataDir + "input.xlsx"); | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Specify the range where you want to search | |
// Here the range is E3:H6 | |
CellArea area = CellArea.createCellArea("E3", "H6"); | |
// Specify Find options | |
FindOptions opts = new FindOptions(); | |
opts.setLookInType(LookInType.VALUES); | |
opts.setLookAtType(LookAtType.ENTIRE_CONTENT); | |
opts.setRange(area); | |
Cell cell = null; | |
do { | |
// Search the cell with value search within range | |
cell = worksheet.getCells().find("search", cell, opts); | |
// If no such cell found, then break the loop | |
if (cell == null) | |
break; | |
// Replace the cell with value replace | |
cell.putValue("replace"); | |
} while (true); | |
// Save the workbook | |
workbook.save(dataDir + "output.xlsx"); |