//Generic Function to Excel Read
public Object[][] excelRead(String filePath ,String fileName,String sheetName ) throws IOException
{
Object data[][] =null;
File file=new File(filePath+"\\"+fileName);
System.out.println(file);
InputStream fis=new FileInputStream(file);
Workbook workbook=null;
String fileExtension=fileName.substring(fileName.indexOf("."));
if(fileExtension.equals(".xlsx"))
{
workbook=new XSSFWorkbook(fis);
}
else if(fileExtension.equals(".xls"))
{
workbook=new HSSFWorkbook(fis);
}
Sheet sheet=workbook.getSheet(sheetName);
int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();
Row row=sheet.getRow(0);
int colCount=row.getLastCellNum();
data = new Object[rowCount+1][colCount];
for (int i=0; i<rowCount+1;i++) { for ( int j=0;j<colCount;j++) { Cell cell=row.getCell(j); if(cell.getCellType()==Cell.CELL_TYPE_STRING)
{ System.out.println(cell.getStringCellValue()); data[i][j]=cell.getStringCellValue(); //return data; } if(cell.getCellType()==cell.CELL_TYPE_NUMERIC) { System.out.println(cell.getNumericCellValue()); data[i][j]=cell.getStringCellValue(); } //System.out.println(row.getCell(j).getStringCellValue()+"||"); } } System.out.println(data.length); return data;
}
//Call to function
Excel excel=new Excel();
Object[][] data=excel.excelRead(FilePath,"ExcelReadFile.xlsx","sheet");
public Object[][] excelRead(String filePath ,String fileName,String sheetName ) throws IOException
{
Object data[][] =null;
File file=new File(filePath+"\\"+fileName);
System.out.println(file);
InputStream fis=new FileInputStream(file);
Workbook workbook=null;
String fileExtension=fileName.substring(fileName.indexOf("."));
if(fileExtension.equals(".xlsx"))
{
workbook=new XSSFWorkbook(fis);
}
else if(fileExtension.equals(".xls"))
{
workbook=new HSSFWorkbook(fis);
}
Sheet sheet=workbook.getSheet(sheetName);
int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();
Row row=sheet.getRow(0);
int colCount=row.getLastCellNum();
data = new Object[rowCount+1][colCount];
for (int i=0; i<rowCount+1;i++) { for ( int j=0;j<colCount;j++) { Cell cell=row.getCell(j); if(cell.getCellType()==Cell.CELL_TYPE_STRING)
{ System.out.println(cell.getStringCellValue()); data[i][j]=cell.getStringCellValue(); //return data; } if(cell.getCellType()==cell.CELL_TYPE_NUMERIC) { System.out.println(cell.getNumericCellValue()); data[i][j]=cell.getStringCellValue(); } //System.out.println(row.getCell(j).getStringCellValue()+"||"); } } System.out.println(data.length); return data;
}
//Call to function
Excel excel=new Excel();
Object[][] data=excel.excelRead(FilePath,"ExcelReadFile.xlsx","sheet");
1 Comments
Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.DataScience with Python Training in Bangalore
ReplyDelete