解決方案,http://jakarta.apache.org/poi/ 裏面可以下載到開發包,還有例子程序,用起來還是很方便的!
下面是一個將Oracle數據庫表導出爲Excel的程序:
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell; //單元格
import org.apache.poi.hssf.usermodel.HSSFCellStyle; //單元格樣式
import org.apache.poi.hssf.usermodel.HSSFDataFormat;//數據格式
import org.apache.poi.hssf.usermodel.HSSFFont; //字體
import org.apache.poi.hssf.usermodel.HSSFHeader; //頭
import org.apache.poi.hssf.usermodel.HSSFRow; //行
import org.apache.poi.hssf.usermodel.HSSFSheet; //一張記事簿
import org.apache.poi.hssf.usermodel.HSSFWorkbook; //一個excel
import org.apache.poi.hssf.util.HSSFColor; //顏色
import java.sql.*;
public class Test{
public static void main(String[] args) throws Exception
{
String filename = "dept.xls";
String column_name="";
PreparedStatement ps=null; //預編譯
Connection conn=null; //連接
Statement smt=null; //sql語句
ResultSet rs = null,rs1=null; //結果集合
ResultSetMetaData md = null;
long rowCount =0l; //總行數
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(Exception e){
e.printStackTrace();
}
String url = "jdbc:oracle:thin:@172.18.2.114:1521:MIS";
String userName = "scott";
String password = "tiger";
conn = DriverManager.getConnection (url, userName, password);
smt = conn.createStatement();
//取得總記錄數
String sql="select deptno,dname,loc from dept";
String sqlqeury="select count(*) as total from ( "+sql+" )";
try{
rs = smt.executeQuery(sqlqeury);
if(rs.next()){
rowCount =rs.getLong("total");
System.out.print(rowCount) ; //記錄總數
}
}catch(Exception e){
System.out.print("aaa");
e.printStackTrace();
System.out.println(e.getMessage());
conn.close(); //異常後關閉連接
throw new Exception("獲得記錄總數失敗");
}
//處理sql語句
try{
rs1 = smt.executeQuery(sql);
md = rs1.getMetaData();
System.out.print(md.getColumnCount());
}catch(Exception e){
System.out.print("bbb");
e.printStackTrace();
System.out.println(e.getMessage());
conn.close(); //異常後關閉連接
throw new Exception("傳入的SQL無法處理");
}
//生成excel代碼
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = null;
HSSFCell cell=null;
for(long i =0;i<=rowCount;i++){
row = sheet.createRow((short)i); //創建一個行
for(int j =0;j<md.getColumnCount();j++){
cell = row.createCell((short)j); //創建單元格
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
if(i==0){
cell.setCellValue(md.getColumnName(j+1)); //設定單元格的值
}else{
cell.setCellValue(rs1.getString(j+1)); //設定單元格的值
}
}
rs1.next();
}
//寫到excel中!
FileOutputStream fileOut = new FileOutputStream(filename);
wb.write(fileOut); //向fileout文件寫
fileOut.close(); //關閉文件輸出流
conn.close(); //關閉正常連接
}
}