A Java Program to retrieve the data from an excel file?
Below is the code to read .xlsx file.XSSFWorkbook -> to read .xlsx file (Microsoft Excel 2003 and earlier)
HSSFWorkbook -> to read .xls file (Microsoft Excel 2007 and later)
public class ExcelDataRead {
public static void main(String[] args) {
try{
InputStream file=new FileInputStream("C:\\Users\\user\\Documents\\testdata.xlsx");
XSSFWorkbook workbook=new XSSFWorkbook(file);
XSSFSheet sheet=workbook.getSheet("Sheet1");
Iterator<Row> rows=sheet.rowIterator();
while(rows.hasNext()) {
XSSFRow row = (XSSFRow)rows.next();
Iterator<Cell> cells=row.cellIterator();
while(cells.hasNext()) {
XSSFCell cell=(XSSFCell)cells.next();
if(cell.getCellType()==CellType.STRING) {
System.out.print(cell.getStringCellValue());
}else if(cell.getCellType()==CellType.NUMERIC){
System.out.print(cell.getNumericCellValue());
}
}
}
workbook.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE: if you are using version greater than 3.15v then replace CellType.STRING with XSSFCell.CELL_TYPE_STRING
0 comments:
Post a Comment