To compare two Excel workbooks in Java, you must use a library like Apache POI to load both files into memory, iterate through the sheets and rows, and compare the cell values using a conditional logic loop. Because Java cannot natively read .xlsx or .xls files, Apache POI acts as the bridge that translates the binary Excel format into Java objects that can be analyzed and compared for differences.
What You'll Need
- Java Development Kit (JDK): Version 8 or higher installed and configured in your system path.
- Integrated Development Environment (IDE): Such as IntelliJ IDEA, Eclipse, or VS Code.
- Apache POI Libraries: Specifically
poiandpoi-ooxmlto handle both older .xls and newer .xlsx formats. - Build Tool: Maven or Gradle to manage the Apache POI dependencies and their transitive requirements.
- Two Excel Files: The source and target workbooks you intend to compare.
Step-by-Step
- Configure Project Dependencies: Add the Apache POI dependencies to your
pom.xml(for Maven) orbuild.gradle(for Gradle). You needpoifor the general API andpoi-ooxmlfor the XML-based .xlsx format. Ensure you include thepoi-ooxml-fullorpoi-ooxml-litedepending on whether you need full schema support. - Initialize Workbook Objects: Use the
WorkbookFactory.create(File file)method. This is the safest approach becauseWorkbookFactoryautomatically detects whether the file is an HSSF (.xls) or XSSF (.xlsx) workbook and returns the appropriateWorkbookinterface, preventing the need for separate logic for different file extensions. - Iterate Through Sheets: Since workbooks can contain multiple sheets, you must decide if you are comparing sheets by index (e.g., Sheet 1 vs Sheet 1) or by name (e.g., "Sales" vs "Sales"). Use a
forloop to iterate through the number of sheets in the first workbook and retrieve the corresponding sheet from the second workbook. - Implement Row Iteration: Within each sheet, use a nested loop to iterate through the rows. Use
sheet.getLastRowNum()to determine the boundary. It is critical to handle null rows; if one workbook has a row that the other lacks, thegetRow()method will return null, which will cause aNullPointerExceptionif not checked. - Extract and Normalize Cell Values: Create a helper method to get the cell value as a String. Excel cells can be numeric, boolean, string, or formula-based. Use a
DataFormatterobject from Apache POI. Theformatter.formatCellValue(cell)method is the most practical choice because it converts any cell type into a String exactly as it appears in the Excel UI, avoiding the complexity of manually checkingcell.getCellType()for every single cell. - Perform the Comparison: Compare the formatted strings of the two cells using
.equals(). If the strings differ, record the sheet name, row index, column index, and the two conflicting values. Store these differences in a List of custom "Difference" objects for reporting. - Handle Dimensional Mismatches: Check if the two sheets have different dimensions. If Workbook A has 10 rows and Workbook B has 12, the loop based on Workbook A will miss the extra rows in Workbook B. To solve this, find the maximum row count between both sheets and iterate up to that maximum, treating missing cells as empty strings.
- Output the Results: Once the loops finish, iterate through your list of differences. You can print these to the console, write them to a log file, or even generate a third "Difference Report" Excel file where the mismatched cells are highlighted in red.
- Close Resources: Wrap your workbook objects in a try-with-resources block or explicitly call
workbook.close()to release the file handles and memory.
Common Mistakes
One of the most frequent errors is neglecting the DataFormatter and attempting to use cell.getStringCellValue() on a numeric cell. This will throw an IllegalStateException because Java cannot implicitly cast a numeric cell to a string. Always use a formatter or a switch statement to handle CellType.NUMERIC, CellType.STRING, and CellType.BOOLEAN separately.
Another common mistake is ignoring empty cells. In Apache POI, a cell that has never been edited is not just "empty"; it is null. If you call cell.getStringCellValue() on a null cell, your program will crash. You must always perform a null check on the Row object and the Cell object before attempting to read their values.
Developers also often forget to account for hidden rows or columns. By default, a loop through all rows will include hidden data. If the goal is to compare only what the user sees, you must check row.isZeroHeight() or sheet.isColumnHidden(colIndex).
Tips
To improve performance when comparing massive workbooks (thousands of rows), avoid loading the entire file into memory using the standard XSSFWorkbook. Instead, use the SXSSFWorkbook or the Event API (SAX parser) provided by Apache POI. The Event API reads the XML file as a stream, which drastically reduces the heap memory required and prevents OutOfMemoryError.
For better accuracy, implement a "tolerance" check for numeric values. Because of how floating-point numbers are stored in Excel, two cells might look identical (e.g., 10.5) but differ by a tiny fraction in the background. Instead of using .equals() for numbers, subtract one from the other and check if the absolute difference is less than a small threshold (e.g., 0.0001).
If you need to compare workbooks that are not perfectly aligned (e.g., one has an extra column inserted in the middle), do not use index-based comparison. Instead, use a unique identifier (like an ID column) to map rows between the two files. This ensures you are comparing the same record even if its position has shifted.
Troubleshooting
If you encounter a ClassNotFoundException or NoClassDefFoundError, it is almost always a dependency issue. Ensure that poi-ooxml and poi versions match exactly. Mixing version 5.2.0 of one with 4.1.2 of another will cause runtime crashes. Clean your Maven/Gradle cache and re-import the dependencies.
If the program runs very slowly or freezes, check your JVM heap size. Excel files are compressed XML; when expanded in memory, they can take up 10 to 20 times more space than the file size on disk. Increase your memory allocation using the -Xmx flag (e.g., -Xmx2g) in your IDE run configurations.
If the comparison reports differences that you cannot see in Excel, check for trailing spaces or non-printing characters. Use .trim() on the strings retrieved from the cells to ensure that a cell containing "Data " is treated as equal to a cell containing "Data".
Frequently Asked Questions
Can I compare files with different sheet names?
Yes. Instead of retrieving sheets by name, use workbook.getSheetAt(index). This allows you to compare the first sheet of File A with the first sheet of File B, regardless of what they are named.
Does this method work for password-protected files?
No, the standard WorkbookFactory cannot open encrypted files. You would need to use a library like poi-ooxml in conjunction with a decryption utility or provide the password via a specialized BouncyCastle implementation.
How do I handle cells with formulas?
You have two choices: compare the formula string itself using cell.getCellFormula(), or compare the calculated result using formatter.formatCellValue(cell). Most users prefer comparing the result.
Is there a way to compare only specific columns?
Yes. In your cell iteration loop, instead of looping from 0 to getLastCellNum(), simply specify the exact column indices you want to check (e.g., if (colIndex == 0 || colIndex == 5) { ... }).
Can I use this for CSV files?
No. Apache POI is specifically for Excel binary and XML formats. For CSV files, you should use a library like OpenCSV or Apache Commons CSV, as CSVs are plain text and do not require the complex object model of a workbook.
What is the best way to report differences?
The most professional approach is to create a new Excel workbook where you copy the original data and change the background color of the cells that differ to yellow or red, then save this as a "Comparison Report" file.