範囲内のデータを検索および置換する
Contents
[
Hide
]
時には、特定の範囲内のデータを検索して置換する必要があります。Aspose.Cellsを使用すれば、検索を特定の範囲に制限することができます。この記事ではその方法について説明します。
Aspose.Cellsではデータを検索する際に範囲を指定するための FindOptions.setRange() メソッドを提供します。
例えば、「search」という文字列を検索して「replace」に置換したい場合、「E3:H6」という範囲内でのみ置換したいとします。以下のスクリーンショットでは、「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"); |