在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");
}
每当您运行此程序时,您似乎正在用新文件覆盖现有文件。
根据XSSF文档,XSSFWorkbook创建的方法签名可以打开现有文件而不是制作新文件。
尝试以下内容:
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("C:\Users\lenovo\workspace\ApachePoi\exceldatabase16.xlsx"));