Saturday, 4 June 2016

How to verify excel sheet present or not in apache poi



By using below code we can verify the perticular excel sheet present or not. If not available we can create by using apache POI command.



code:

public static void main(String agrs[])
{

Workbook book2=verifyExcelVersion(ToFilePath);
Sheet sheet2=null;


if(!isExcelSheetExist(wb,"Sheet2"))
createExcelSheet(wb,"Sheet2",Download_FilePath);

}


// verify Excel Sheet exist or not

public static boolean isExcelSheetExist(Workbook wb, String SheetName)
{
if(wb.getSheetIndex(SheetName)>=0)
return true;
else
return false;

}


// create new Excel sheet in workbook

public static void createExcelSheet(Workbook wb, String SheetName, String ExcelPath) throws IOException
{
wb.createSheet(SheetName);
FileOutputStream output_file =new FileOutputStream(new File(ExcelPath));  
wb.write(output_file); 
output_file.flush();
output_file.close(); 

}


// verify Excel version

public static Workbook verifyExcelVersion(String FilePath) throws FileNotFoundException, IOException
{
Workbook book1=null;
String fileExtn=FilenameUtils.getExtension(FilePath);

if(fileExtn.equals("xls"))
book1=new HSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsx"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsm"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
return book1;
}




No comments:

Post a Comment