导出数据库查询结果到Excel使用Apache POI [英] Exporting database query results to excel using apache poi
本文介绍了导出数据库查询结果到Excel使用Apache POI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过一些样本codeS去导出数据使用Apache POI脱颖而出。但是,我不知道,就是我们如何能够数据库查询结果导出到Excel文件。我知道,我们必须创建行单元格,然后设置值的单元格。但我已经在结果的数据,并且必须只导出同一个Excel文件。谁能给我提供一个小/易code做同样的。
I went through some sample codes to export data to excel using Apache POI. However, I am not sure as to how we can export database query results to an excel file. I know that we must create cells in rows and then set values to the cell. But I already have the data in the resultset and must just export the same to an excel file. Can anyone provide me a small/easy code to do the same.
谢谢!
推荐答案
尝试:参考的Apache POI的开发者指南
例如Person表:
+------------------+
| NAME | ADDRESS |
+------------------+
| Jhone | USA |
| Smith | USA |
+------------------+
示例程序
Workbook wb = new HSSFWorkbook();
Sheet personSheet = wb.createSheet("PersonList");
Row headerRow = personSheet.createRow(0);
Cell nameHeaderCell = headerRow.createCell(0);
Cell addressHeaderCell = headerRow.createCell(1);
String sql = "select name, address from person_table";
PrepareStatement ps = connection.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
int row = 1;
while(resultSet.next()) {
String name = resultSet.getString("name");
String address = resultSet.getString("address");
Row dataRow = personSheet.createRow(row);
Cell dataNameCell = dataRow.createCell(0);
dataNameCell.setCellValue(name);
Cell dataAddressCell = dataRow.createCell(1);
dataAddressCell.setCellValue(address);
row = row + 1;
}
String outputDirPath = "D:/PersonList.xls";
FileOutputStream fileOut = new FileOutputStream(outputDirPath);
wb.write(fileOut);
fileOut.close();
这篇关于导出数据库查询结果到Excel使用Apache POI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文