java - 在 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");
}
解决方案
每次运行此程序时,您似乎都在用新文件覆盖现有文件。
根据 XSSF 文档,创建 XSSFWorkbook 的方法签名可以打开现有文件而不是创建新文件。
尝试以下方式:
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("C:\\Users\\lenovo\\workspace\\ApachePoi\\exceldatabase16.xlsx"));
推荐阅读
- xforms - XForms 是如何使用的?
- genexus - 为什么无法从 Genexus .Net 使用某些外部 REST API?
- css - 在材质 UI 中,如何将 Button 置于 Grid 项目的中间?
- javascript - 检查 TypeScript 中的全局或窗口对象上是否存在属性
- google-apps-script - 使用出现错误的 Google 表格 onOpen() 函数时,如何获得实时脚本错误通知?
- prolog - Prolog 作为第一种编程语言
- html - 展开一张卡片时展开所有卡片的高度
- python - 安装 djangocms-blog 后的 ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils .encoding'
- java - 如何从 pagedList 中删除项目
- javascript - 在 python 中运行 javascript 函数