Saturday, November 19, 2011

Get Sheet Names from an Excel File Using Java and POI

To get the sheet names from an Excel file in Java we can use Apache's POI library. First a file is imported from disk passing a FileInputStream object to a org.apache.poi.hssf.usermodel.HSSFWorkbook object. Looping over each sheet in the Excel spreadsheet, the sheet name is determined using the workbook.getSheetName() method. The following sample code was successfully tested with POI versions 3.6 and 3.7.

Here is a screenshot of the test file I used for this example:



import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

// The following example code demonstrates how to get the Sheet
// names in an Excel spreadsheet file

public class GetExcelSheetNames {

    public static void main(String[] args) {

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("/Temp/Test1.xls");

            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);

            // for each sheet in the workbook
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {

                System.out.println("Sheet name: " + workbook.getSheetName(i));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}


Here is the output of the program:
Sheet name: Sheet1
Sheet name: Sheet2
Sheet name: Sheet3
Piece of cake!!!

No comments: