如何将查询结果导出到Excel文件?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将查询结果导出到Excel文件?相关的知识,希望对你有一定的参考价值。

给出以下查询:

     String SQL = "select name,years from person"; 
     ps = con.createStatement();
     rs = ps.executeQuery(SQL);
     jTable1.setModel(DbUtils.resultSetToTableModel(rs));

如何轻松将数据导出到Excel文件?

谢谢

答案
    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文件?的主要内容,如果未能解决你的问题,请参考以下文章

如何将查询结果导出到Excel文件?

在SQL中如何将查询结果直接导出为EXCEL表格

sqlserver 如何将查询结果导出到excel中

在delphi中如何将查询结果导出到excel中

将sql查询结果导出到csv或excel

怎样将SQL数据导出到EXCEL中