Find and Replace Data in Excel in Java

This article demonstrates how to find and replace data in an Excel file using Spire.XLS for Java.

Below is the sample Excel file we used for demonstration:

Find and Replace Data in Excel in Java

import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ReplaceData {
    public static void main(String[] args){

        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("Test.xlsx");

        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //Find all the text "Total" in the worksheet
        CellRange[] ranges = worksheet.findAllString("Total", true, true);

        for (CellRange range : ranges)
        {
            //Replace the text with new text
            range.setText("Sum");
        }

        //Save the resultant file
        workbook.saveToFile("ReplaceData.xlsx", ExcelVersion.Version2013);
    }
}

Output:

Find and Replace Data in Excel in Java