Showing posts with label Excel. Show all posts
Showing posts with label Excel. Show all posts

Thursday, 16 June 2016

JAVA PROGRAM TO READ DATA FROM EXCEL FILE AND INSERTING INTO DATA BASE


public static void uploadExcelFile(String fileName)
{
ArrayList dataHolder = new ArrayList();
try
{
XSSFWorkbook workbook=new XSSFWorkbook(fileName);

/** Get the first sheet from workbook**/
XSSFSheet mySheet = workbook.getSheetAt(0);
                        /** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();

while (rowIter.hasNext())
{
XSSFRow myRow = (XSSFRow) rowIter.next();
                                 Iterator cellIter = myRow.cellIterator();
ArrayList cellStoreArrayList = new ArrayList();
                                while (cellIter.hasNext())
{
XSSFCell myCell = (XSSFCell) cellIter.next();
cellStoreArrayList.add(myCell);
}
                                dataHolder.add(cellStoreArrayList);
}
catch (Exception e) 
{
e.printStackTrace();
}

try 
{
Class.forName("Data Base Driver Class");

                Connection con =null;
con=DriverManager.getConnection("URL","DB User Name","DB Password");
ArrayList cellStoreArrayList = null;

PreparedStatement ps= null;
                        ps=con.prepareStatement("insert into registration values(?,?,?,?)");
                        for (i= 1; i < dataHolder.size(); i++) 
                       {
ps.setString(1,((XSSFCell) cellStoreArrayList.get(0)).toString());
ps.setString(2,((XSSFCell) cellStoreArrayList.get(1)).toString());
                                ps.setString(3,((XSSFCell) cellStoreArrayList.get(2)).toString());
        ps.setString(4,((XSSFCell) cellStoreArrayList.get(3)).toString());
   
ps.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
}
}