0

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

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 ); 
   } 

  }
  }
4

1 回答 1

1

我已经重写了如下代码,现在它可以工作了。

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

            Row row = sheet1.createRow(i);

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

            i++;
            }
             wb.write(fileOut);  
于 2012-12-06T09:14:10.667 回答