/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package invcompare;
import java.sql.Connection;
import java.sql.Statement;
import java.io.File;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
* <li>把数据导入到Excel公用类</li> </br> This is about
* <code>ExcelUtil</code>
*
* @author hjy273
* @version 1.0 @date Sep 6, 2008 9:52:52 PM
*/
public class ExcelUtil {
LogInfo loginfo = new LogInfo();
public ExcelUtil() {
}
public boolean DB2Excel(ResultSet rs, String filePath) {
boolean flag = false;
WritableWorkbook workbook = null;
WritableSheet sheet = null;
Label label = null;
// 创建Excel表
try {
workbook = Workbook.createWorkbook(new File(filePath));
//workbook = Workbook.createWorkbook(os);
// 创建Excel表中的sheet
sheet = workbook.createSheet("INV_WMS_SAP", 0);
// 向Excel中添加数据
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
String colName = null;
int row = 0;
// 添加标题
for (int i = 0; i < columnCount; i++) {
colName = rsmd.getColumnName(i + 1);
label = new Label(i, row, colName);
// loginfo.appendLog("标题:"+i+"---"+row +"---"+ colName);
sheet.addCell(label);
}
row++;
while (rs.next()) {
for (int i = 0; i < columnCount; i++) {
label = new Label(i, row, rs.getString(i + 1));
sheet.addCell(label);
}
row++;
}
//sheet.setRowView(0, 200);
// 关闭文件
workbook.write();
workbook.close();
workbook = null;
flag = true;
} catch (SQLException e) {
loginfo.appendLog(e.getMessage());
} catch (RowsExceededException e) {
loginfo.appendLog(e.getMessage());
} catch (WriteException e) {
loginfo.appendLog(e.getMessage());
} catch (IOException e) {
loginfo.appendLog(e.getMessage());
} finally {
try {
workbook.close();
} catch (Exception e) {
}
}
return flag;
}
/**
* 测试方法
*
* @param args
*/
public static void main(String[] args) {
// write your code
String url = "jdbc:oracle:thin:@100.100.100.100:1521:wms";
String userName = "wmprod";
String password = "wmprod";
Connection conn;
Statement stmt;
ResultSet rset;
try {
try {
Class<?> forName = Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (Exception e) {
System.out.println("No Driver!");
}
// Connect to the database
conn = DriverManager.getConnection(url, userName, password);
// Create a Statement
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from vendor_master");
if (!new ExcelUtil().DB2Excel(rs, "d:/1.xls")) {
System.out.println("数据写入失败");
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}