首页 > 解决方案 > 在 java eclipse 中,我从数据库中检索数据并粘贴到已经存在的 excel 中。已经存在的数据将被删除

问题描述

在 java eclipse 中,我运行了一个查询以从数据库中检索数据并粘贴到 C 驱动器中已经存在的 excel 表(exceldatabase16)中。已经存在的 excel -exceldatabase16 在第一行包含列名。粘贴到 exceldatabase16 中的数据是从第 6 行和 F 列粘贴的。但第 1 行的数据仍然被删除。

public static  void retrieveData1( Connection connection) throws SQLException, IOException 
    {
         Statement stmt = null;
           ResultSet rs = null;
         stmt = connection.createStatement();


         rs = stmt.executeQuery("SELECT * FROM countries where region_id='3' ");
//         getColumnNames(rs);


         XSSFWorkbook workbook = new XSSFWorkbook(); 
         XSSFSheet spreadsheet = workbook.createSheet("countriesdetails");
         XSSFRow row = spreadsheet.createRow(5);
         XSSFCell cell;
         cell = row.createCell(5);

         cell.setCellValue("country id");
         cell = row.createCell(6);
         cell.setCellValue("country name");
         cell = row.createCell(7);
         cell.setCellValue("region");

         int i = 6;

         while(rs.next()) {
            row = spreadsheet.createRow(i);
            cell = row.createCell(5);      
            cell.setCellValue(rs.getString(1));

            cell = row.createCell(6);
            cell.setCellValue(rs.getString(2));
            cell = row.createCell(7);
            cell.setCellValue(rs.getInt(3));

            i++;
         }

         FileOutputStream out = new FileOutputStream(new File("C:\\Users\\lenovo\\workspace\\ApachePoi\\exceldatabase16.xlsx"));
         workbook.write(out);
         out.close();
         workbook.close();
         System.out.println("exceldatabase.xlsx written successfully");     
     }

标签: javaapache-poi

解决方案


每次运行此程序时,您似乎都在用新文件覆盖现有文件。

根据 XSSF 文档,创建 XSSFWorkbook 的方法签名可以打开现有文件而不是创建新文件。

尝试以下方式:

 XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("C:\\Users\\lenovo\\workspace\\ApachePoi\\exceldatabase16.xlsx"));

推荐阅读