Tuesday, October 9, 2012

How to read Excel file using Java (.xls extension)

This tutorial will work only for Excel .xls (MS 2003) extension **

1. Download jexcelapi jxl.jar from here. This download contain full project, just take the jxl.jar file and put in your workspace.
2. Create one excel file say Binod.xls and put some data.
3. Write ExcelReader.java and put ExcelReader.java and Binod.xls both file is same folder.

ExcelReader.java
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ExcelReader {

public static void main(String[] args) throws IOException {
String fileName = "Binod.xls";
File file = new File(fileName);
ExcelReader excelReader = new ExcelReader(); excelReader.read(file);
}

public void read(File inputWorkbook) throws IOException {
Workbook workbook;
try {
workbook = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = workbook.getSheet(0);
// System.out.println("No of Columns :: "+sheet.getColumns());
for (int j = 0; j < sheet.getRows(); j++) {
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell = sheet.getCell(i, j);
CellType type = cell.getType();
if (cell.getType() == CellType.LABEL) { System.out.print(cell.getContents() + " "); }
else if (cell.getType() == CellType.NUMBER) {System.out.print(cell.getContents() + " "); }
else { System.out.print(cell.getContents() + " "); }
}
System.out.println("\n"); }
} catch (BiffException e) { e.printStackTrace(); }
}
}

1 comments:

You can read excel file by using Aspose.Cells for Java Library and can also create, modify or even convert excel file to many other format.

Post a Comment