I have to export data from database to excel sheet by using java.I have around 500+ column in DB, so need help in code where i need not to put the column name. I got some code from internet, but its specific to particular column name, if i implement in that way there will be lot of manual work.Any suggestion on code?
import java.io.*;
import java.sql.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
public class DatabaseTesting{
public static void main(String[]args){
try{
String filename="c:/data.xls" ;
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
//HSSFRow rowhead= sheet.createRow((short)0);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from employee");
XSSFRow row = spreadsheet.createRow(1);
XSSFCell cell;
// use ResultSetMetaData to fetch the column names
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int c=1; c <= columnCount; ++c) {
String name = rsmd.getColumnName(c);
cell = row.createCell(c);
cell.setCellValue(name);
}
int i = 2;
while (resultSet.next()) {
row = spreadsheet.createRow(i);
for (int c=1; c <= columnCount; ++c) {
cell = row.createCell(c);
cell.setCellValue(resultSet.getObject(C));
}
}
System.out.println("Your excel file has been generated!");
} catch ( Exception ex ) {
System.out.println(ex);
}
}
}