how to read an excel sheet through rows and columns using jexcel

how to read an excel sheet through rows and columns using jexcel

Previous Home Next

 

This example demonstrates how can you read in the excel worksheet of an existing workbook simply by looping throught the rows and columns not by reading the values on the cell by cell basis.

For reading a worksheet you should import the jxl.read.biff package. 
 We have created a main method in which we are accessing the values contained in a worksheet through the loop.

We have created a class named ReadByRowColsSheetXL, in which we have created a main class to read in the values contained in a sheet of an existing workbook the means of simple loop.

 
package r4r.co.in;
import jxl.*;
import jxl.biff.formula.FormulaException;
import jxl.read.biff.*;
import java.io.File;
import java.io.IOException;
import jxl.write.WriteException;
import java.util.Locale;

public class ReadByRowsColsSheetXL {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException, WriteException, BiffException, FormulaException{
		// TODO Auto-generated method stub
        try
        {
        	File f1=new File("F:/JAVA PROJECTS/Jexcel/src/r4r/co/in/firstsheet.xls");
        	WorkbookSettings ws=new WorkbookSettings();
        	ws.setLocale(new Locale("er","ER"));
        	Workbook workbook=Workbook.getWorkbook(f1,ws); //opening an existing workbook 
        	
        	Sheet readsheet=workbook.getSheet(0);
        	System.out.println(readsheet.getName());    // getting the name of sheet contained in the workbook
        	
        	int i=0,j=0;
        	for(j=0;j<(readsheet.getColumns());j++)        // using for loop to move in through columns
        	for(i=0;i<readsheet.getRows();i++)             // using for loop to move in through rows
        	{
        		if(readsheet.getCell(j,i).getType()==(CellType.LABEL))     // if cell is Label then, 
        		{
        			System.out.println(readsheet.getCell(j,i).getContents());     // get its content
        		}
        		if(readsheet.getCell(j,i).getType()==(CellType.NUMBER))    // if cell is of type Number then,
        	
        			System.out.println(readsheet.getCell(j,i).getContents());    // get its content
        		}
        		if (readsheet.getCell(j, i).getType()==(CellType.NUMBER_FORMULA))    // if cell is of type Number Formula then,
        		{
        		System.out.println(readsheet.getCell(j,i).getContents());      // get its content
        		}
        		
            }
        catch(IOException e)
        {
        	e.printStackTrace();
        }
        
        catch(BiffException e)
        {
        	e.printStackTrace();
        }
      
	}

}


Previous Home Next