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