我必须使用Java将数据从数据库导出到Excel工作表.DB中我有大约500+列,因此在代码中需要帮助的地方不需要放置列名。我从互联网上获得了一些代码,但是它特定于特定的列名,如果我以这种方式实现,将需要大量的人工工作。对代码有任何建议吗?
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);
}
}
}
答案 0 :(得分:0)
ResultSet
类除了我们熟悉的命名getter外,还公开了接受列索引(从位置1开始)的getter。您可以在这里利用它:
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));
}
}
注意:
如果查看对XSSFCell#setCellValue()
的调用,您会发现我正在使用ResultSet#getObject
来获取值。原因是,我们不知道数据库列将是哪种列类型。我在这里假设setCellValue
可以接受Object
作为输入。如果没有,那么您将不得不使用一些替代方法,例如随时随地使用ResultSet#getString()
。