简体   繁体   中英

jdbc apache poi create xls file

i have written the following program to get list of tables from postgres database and write them into a xls file. i have included the Apache poi library to write xls file. the program is running with out any error, the is also created but the output is not written into the file the file is just empty. plz help me to write the resultset into the file.

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

  }
  }

i have rewritten the code as below and now it works.

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

            Row row = sheet1.createRow(i);

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM