I need to export result of a resultset into an excel sheet using java. Resultset contains a table with thousands of rows and multiple columns. If someone could provide a sample code that will be very useful as I am stuck with this problem. Below is the sample code that I am using to achieve this but somehow not able to get correct data in excel file:-
SSFWorkbook workbook = new XSSFWorkbook();
try {
setConnection(appDB);
String queryName="SELECT * FROM ALL_TABLES where table_name='table_name'";
Reporter.addStepLog("----------------------------------- " + queryName.toUpperCase()
+ "\n - Validation Start" + " -----------------------------------");
ps = con.prepareStatement(queryName, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = ps.executeQuery();
Statement statement = con.createStatement();
XSSFSheet spreadsheet = workbook.createSheet("employedb");
ResultSet resultSet = statement.executeQuery("select * from all_tab_columns where table_name='table_name'");
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;
int cc=resultSet.getMetaData().getColumnCount();
for(int i=1;i<=cc;i++)
{
String headerVal=resultSet.getMetaData().getColumnName(i);
headerValues.add(headerVal);
cell = row.createCell(i-1);
cell.setCellValue(resultSet.getMetaData().getColumnName(i));
}
System.out.println(headerValues);
int i = 1;
while (resultSet.next())
{
for(int j=1;j<=cc;j++)
{
System.out.println(resultSet.getString(j));
XSSFRow row1 = spreadsheet.createRow((short) i);
row1.createCell((short) i).setCellValue(resultSet.getString(resultSet.getMetaData().getColumnName(j)));
i++;
}
}
FileOutputStream out = new FileOutputStream(new File("S:\\Downloads\\excel.xlsx"));
workbook.write(out);
out.close();
System.out.println("exceldatabase.xlsx written successfully");
}catch(Exception e){}
}
Please let me know if the question is not clear as I am new to this forum.