Open and read Excel file in Java

GemBox.Spreadsheet for Java can open many Excel file formats (including XLS, XLSX, CSV and ODS) in the same manner. Specifically, it uses a ExcelFile.Load method to read from an Excel file or stream in Java.

The following example shows how you can read all ExcelCell objects, their values (ExcelCell.getValue), and CellValueType properties in an ExcelFile object.

Reading Excel Screenshot
Screenshot of Excel cell values read with GemBox.Spreadsheet for Java
Upload your file (Drag file here)
import com.gembox.spreadsheet.*;

class Program {

    public static void main(String[] args) throws java.io.IOException {
        // If using the Professional version, put your serial key below.
        SpreadsheetInfo.setLicense("FREE-LIMITED-KEY");

        ExcelFile workbook = ExcelFile.load("%InputFileName%");

        StringBuilder sb = new StringBuilder();

        // Iterate through all worksheets in an Excel workbook.
        for (ExcelWorksheet worksheet : workbook.getWorksheets()) {
            sb.append('\n');
            sb.append(String.format("%1$s %2$s %1$s", "-----", worksheet.getName()));

            // Iterate through all rows in an Excel worksheet.
            for (ExcelRow row : worksheet.getRows()) {
                sb.append('\n');

                // Iterate through all allocated cells in an Excel row.
                for (ExcelCell cell : row.getAllocatedCells()) {
                    if (cell.getValueType() != CellValueType.NULL)
                        sb.append(String.format("%1$s [%2$s]           ", cell.getValue(), cell.getValueType()));
                    else
                        sb.append("                        ");
                }
            }
        }

        System.out.println(sb.toString());
    }
}

Note that, when you iterate through all read cells in an ExcelRow, you should use ExcelRow.getAllocatedCells to prevent an unnecessary allocation of ExcelCell objects.

See also


Next steps

GemBox.Spreadsheet for Java is a component that enables you to read, write, edit and convert spreadsheet files from your applications using one simple API.

Download Buy