从数据库读数据写到 xls

【问题】

I need your help in storing the fetched values from a SQL statement to an excel file. I wrote the below code, but I am facing difficulties on how to write the fetched values under the appropriate columns. For example at the beginning, I created 3 headers (ID - Name - Salary). Now, I need to write the fetched values from the SQL statement under each appropriate header, but I do not know how to write them. So kindly assist. The code is:

public void GenerateExcel() {
   Connection conn = null;
   Statement stmt = null;
   FileOutputStream fileOut = new FileOutputStream("C:\\Desktop\\poi-test.xls");
   HSSFWorkbook workbook = new HSSFWorkbook();
   HSSFSheet worksheet = workbook.createSheet("Employee Details");
   HSSFRow row1 = worksheet.createRow((short) 0);
   HSSFCell cellA1 = row1.createCell((short) 0);
   cellA1.setCellValue("ID");
   HSSFCell cellB1 = row1.createCell((short) 1);
   cellB1.setCellValue("Name");
   HSSFCell cellC1 = row1.createCell((short) 1);
   cellC1.setCellValue("Salary");
   try{
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      stmt = conn.createStatement();

      String sql = "SELECT id, name, amount FROM Employee";
      ResultSet rs = stmt.executeQuery(sql);
      while(rs.next()){
         int id  = rs.getInt("id");
         int age = rs.getString("name");
         String first = rs.getInt("amount");
          }
      rs.close();
      workbook.write(fileOut);
      fileOut.flush();
      fileOut.close();
   }catch(SQLException se){
      se.printStackTrace();
   }catch(Exception e){
      e.printStackTrace();
   }finally{
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }
}
}

【回答】

数据库到Excel的问题,并非一定要用java编程去处理,推荐SPL去解决,只需建立数据源并输出数据。如下代码:

A
1$select id, name, amount FROM Employee
2=file("C:\\Desktop\\poi-test.xls ").xlsexport@t(A1)

A1:建立数据源连接

A2:将数据输出到Excel文件

函数xlsexport支持导出为xls或xlsx,@t表示在首行写入字段名。上述代码不仅可以在命令行执行,也很容易集成到JAVA,参考【Java 如何调用 SPL 脚本

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值