Sök och ersätt data i ett intervall
Aspose.Cells tillhandahåller FindOptions.setRange() metoden för att ange ett intervall vid sökning efter data.
Anta att du vill söka efter strängen “sök” och ersätta den med “ersätt” i intervallet E3:H6. I skärmdumpen nedan kan strängen “sök” ses i flera celler men vi vill endast ersätta den i ett givet intervall, här markerat i gult.
Ingångsfil
Efter att koden har körts ser utdatafilen ut som nedan. Alla “sök” strängar inom intervallet har ersatts med “ersätt”.
Utgångsfil
// 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"); |