The code snippet
can be used to process excel files of any format.(xls or xlsx)
The code snippet
can be used in areas where excel file of any format needs to be
uploaded and processes.
The following jars
will be needed to run the code snippet.
- 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
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 JavaApplication3 { public void ReadExcel2007Sheet(String filename) throws Exception { 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 void readOtherExcel(String inputFile) throws IOException { File inputWorkbook = new File(inputFile); Workbook w; try { w = Workbook.getWorkbook(inputWorkbook); // Get the first sheet Sheet sheet = w.getSheet(0); // Loop over columns and lines for (int j = 0; j < sheet.getColumns(); j++) { for (int i = 0; i < sheet.getRows(); i++) { Cell cell = sheet.getCell(j, i); CellType type = cell.getType(); if (cell.getType() == CellType.LABEL) { System.out.println("It is a label " + cell.getContents()); } if (cell.getType() == CellType.NUMBER) { System.out.println("It contains numbers" + cell.getContents()); } } } } catch (BiffException e) { e.printStackTrace(); } } public static void main(String[] args) { JavaApplication3 object=new JavaApplication3(); String filename1 = "Excel2007.xlsx"; int dotposition1= filename1.lastIndexOf("."); String ext1 = filename1.substring(dotposition1 + 1, filename1.length()); if(ext1.equalsIgnoreCase("xlsx")) { try{ object.ReadExcel2007Sheet(filename1); }catch(Exception e) { e.printStackTrace(); } } else if(ext1.equalsIgnoreCase("xls")) { try{ object.readOtherExcel(filename1); }catch(Exception e) { e.printStackTrace(); } } } }