jdbc apache poi创建xls文件

时间:2012-12-06 03:42:08

标签: java postgresql jdbc apache-poi resultset

我编写了以下程序来获取postgres数据库中的表列表并将它们写入xls文件。我已经包含Apache poi库来编写xls文件。程序运行时没有任何错误,也会创建,但输出不会写入文件,文件只是空的。 plz帮我把结果集写入文件。

package list;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class List 
{
 public static void main(String[] args) throws SQLException, FileNotFoundException,   IOException 
{

 Connection con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/db","user","pass");

  DatabaseMetaData md = con.getMetaData();
  ResultSet rs = md.getTables(null, "public", "%", null);

  try (FileOutputStream fileOut = new FileOutputStream("/home/usr/Desktop/list.xls")) 
  {

            Workbook wb = new HSSFWorkbook();
            Sheet sheet1 = wb.createSheet("Table List");
            Row row = sheet1.createRow(250);
            while (rs.next()) 
            {
    row.createCell(0).setCellValue(rs.getString(3));

            }
             wb.write(fileOut);  
             fileOut.close();

  }
  catch(SQLException e) 
   { 
       System.out.println( "could not get JDBC connection : " + e ); 
   } 

  }
  }

1 个答案:

答案 0 :(得分:1)

我已经重写了下面的代码,现在它可以正常工作。

            int i = 0;
                while (rs.next()) 
            {

            Row row = sheet1.createRow(i);

            row.createCell(0).setCellValue(rs.getString(3));

            i++;
            }
             wb.write(fileOut);