解决方案, 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(); //关闭正常连接
}
}
2004.12.22
ladofwind@163.com