导出Oracle表数据到Excel

时间:2022-12-09 00:48:59
package com.rjsoft.query.workflow.util;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import java.io.File;
import java.io.IOException;
import java.sql.*;

/**
* Created by Administrator on 2015/10/15.
*/
public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException, WriteException {
System.out.println(1);

Connection con = null;
PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
ResultSet result = null;// 创建一个结果集对象
Class.forName("oracle.jdbc.driver.OracleDriver");//加入oracle的驱动,“”里面是驱动的路径

String url = "jdbc:oracle:thin:@//127.0.0.1:1521/RAC";// 数据库连接,oracle代表链接的是oracle数据库;thin:@MyDbComputerNameOrIP代表的是数据库所在的IP地址(可以保留thin:);1521代表链接数据库的端口号;ORCL代表的是数据库名称
//注意:新版本的地址格式"jdbc:oracle:thin:@//127.0.0.1:1521/RAC"
//老版本的地址格式
"jdbc:oracle:thin:@127.0.0.1:1521:ORCL"



String UserName = "xx";// 数据库用户登陆名 ( 也有说是 schema 名字的 )  
String Password = "xx";// 密码  
con = DriverManager.getConnection(url, UserName, Password);        
System.out.println("连接成功");        String sql = "select * from wf t ";// 预编译语句,代表参数 pre = con.prepareStatement(sql);// 实例化预编译语句 //pre.setString(1, "刘显安");// 设置参数,前面的1表示参数的索引,而不是表中列名的索引 result = pre.executeQuery();// 执行查询,注意括号中不需要再加参数 WritableWorkbook book = Workbook.createWorkbook(new File("C:\\test.xls"));        WritableSheet sheet = book.createSheet("第一页", 0);        int row = 0;        while (result.next()){            String var1 = result.getString(1);            String var2 = result.getString(2);            String var3 = result.getString(3);            String var4 = result.getString(4);            Label label1 = new Label(0, row, var1);            Label label2 = new Label(1, row, var2);            Label label3 = new Label(2, row, var3);            Label label4 = new Label(3, row, var4);            sheet.addCell(label1);            sheet.addCell(label2);            sheet.addCell(label3);            sheet.addCell(label4);            row++;        }        book.write();        book.close();    }    }