Sök och ersätt data i ett intervall
Contents
[
Hide
]
Ibland måste du söka efter och ersätta specifik data i ett intervall och ignorera eventuella cellvärden utanför det önskade intervallet. Aspose.Cells låter dig begränsa en sökning till ett specifikt område. Den här artikeln förklarar hur.
Aspose.Cells tillhandahållerFindOptions.setRange() metod för att ange ett intervall när du söker efter data.
Anta att du vill söka efter strängen**“Sök”** och byt ut den mot**“byta ut”** innom räckhåll**E3:H6**. I skärmdumpen nedan kan strängen “sök” ses i flera celler men vi vill ersätta den endast i ett givet intervall, här markerat med gult.
Indatafil
Efter exekvering av koden ser utdatafilen ut som nedan. Alla “sök”-strängar inom intervallet har ersatts med “ersätt”.
Utdatafil
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"); |