以下代码我没有真正去实践,紧做为总结,方便以后查阅:
这种方法需要设置ODBC源.....
参考:
http://xytang.blogspot.com/2008/02/how-to-connect-to-excel-spreadsheet.html
http://www.devx.com/Java/Article/17848
http://www.java2s.com/Tutorial/Java/0340__Database/UseJDBCODBCbridgetoreadfromExcel.htm
附代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element; /**
* 这种读取Excel的方式应该配配置ODBC数据源.
* @author CDV-DX7
*
*/
public class ExcelUtil {
private String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
private String dataSourceUrl = "jdbc:odbc:driver={Microsoft Excel Driver (*.xls)};DBQ="; // 不设置数据源 public ExcelUtil(){} public void setDriverName(String driverName){
this.driverName = driverName;
} /**
* 从excel中获取数据,转化为XML
* @param excelUrl
* @param sheetName
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public Document getExcelData(String excelUrl, String sheetName)
throws ClassNotFoundException, SQLException {
Connection dbConn = null;
try {
Class.forName(this.driverName);
excelUrl = this.dataSourceUrl + excelUrl;
dbConn = DriverManager.getConnection(excelUrl, "", "");
Statement smt = dbConn.createStatement();
ResultSet rs = smt.executeQuery("select * from [" + sheetName + "$]");
Document doc = DocumentHelper.createDocument();
Element elmRoot = doc.addElement("Tab");
while (rs.next()) {
Element elmRow = elmRoot.addElement("Row"); int colNum = rs.getMetaData().getColumnCount();
for (int i = 1; i <= colNum; i++) {
Element elmCol = elmRow.addElement("Col");
elmCol.setText(rs.getString(i));
}
} return doc;
} finally {
dbConn.close();
}
} public static void main(String[] args) {
try{
//使用方法示例
String excelUrl = "C:\\Users\\CDV-DX7\\Desktop\\节目信息输入数据.xls";
String sheetName = "节目列表";
ExcelUtil excelutil = new ExcelUtil();
excelutil.getExcelData(excelUrl,sheetName);
}catch (Exception e){
e.printStackTrace();
System.out.println("出错啦:"+e.getMessage());
}
}
}