在 Excel 中使用 C# 代码搜索和替换范围内的数据
Contents
[
Hide
]
有时,您需要在范围内搜索并替换特定数据,忽略范围之外的任何单元格值。Aspose.Cells允许您把搜索限制在特定范围内。本文将对此进行详细解释。
Aspose.Cells 提供了用于在搜索数据时指定范围的 FindOptions.setRange() 方法。
假设您想要在范围E3:H6中搜索字符串**“search”**并将其替换为**“replace”**。在下面的屏幕截图中,可以看到字符串"search"出现在多个单元格中,但我们只想在给定范围内进行替换,此处用黄色突出显示。
输入文件
执行代码后,输出文件的外观如下。范围内的所有"search"字符串都已被替换为"replace"。
输出文件
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(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"); |