如何将查询结果导出到 Excel 文件?
Posted
技术标签:
【中文标题】如何将查询结果导出到 Excel 文件?【英文标题】:How do I export the result of a query to an Excel file? 【发布时间】:2018-04-15 16:23:31 【问题描述】:给定以下查询:
String SQL = "select name,years from person";
ps = con.createStatement();
rs = ps.executeQuery(SQL);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
如何轻松将数据导出到 Excel 文件?
谢谢
【问题讨论】:
【参考方案1】: try Apache POI... http://poi.apache.org/
Workbook wb = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Java Books");
// create header row
HSSFRow headerRow = sheet.createRow(0)
Cell nameHeaderCell = headerRow.createCell(0);
Cell addressHeaderCell = headerRow.createCell(1);
String sql = "select name, address from student";
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 = sheet.createRow(row);
Cell dataCell = dataRow.createCell(0);
dataCell.setCellValue(name);
Cell dataAddressCell = dataRow.createCell(1);
dataAddressCell.setCellValue(address);
row = row + 1;
String outputDirPath = "";//PATH for export location
FileOutputStream fileOut = new FileOutputStream(outputDirPath);
wb.write(fileOut);
fileOut.close();
【讨论】:
以上是关于如何将查询结果导出到 Excel 文件?的主要内容,如果未能解决你的问题,请参考以下文章