Reading a xlsx (Excel2007) file in java


You may need to include some of the jar files like
  • xmlbeans-2.3.0.jar
  • dom4j-1.1.jar
  • poi-ooxml-schemas-3.6-20091214.jar
  • poi-ooxml-3.6-20091214.jar
  • poi-3.6-20091214.jar
You can google it and download and include it along with the below code.
You have to include a simple xlsx file with some values in it (string values) and run the code.  This code will fetch the values and print it on the screen.


import org.apache.poi.xssf.usermodel.XSSFWorkbook; 
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import java.util.Iterator;
import java.io.*;
public class Main {

 
    public void ReadSheet() throws Exception
    {
        String filename = "book1.xlsx";
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filename);
            
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Iterator rows = sheet.rowIterator();
            int number=sheet.getLastRowNum();
            System.out.println(" number of rows"+ number);
            while (rows.hasNext())
            {

                XSSFRow row = ((XSSFRow) rows.next());
                Iterator cells = row.cellIterator();
                while(cells.hasNext())
                {
                    XSSFCell cell = (XSSFCell) cells.next();
                    String Value=cell.getStringCellValue();
                    System.out.println(Value);
                }
             }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
       
    }
    public static void main(String[] args) {

        Main object=new Main();
        try{
        object.ReadSheet();

        }catch(Exception e)
        {
            e.printStackTrace();
        }
}

}

0 comments: