日期:2014-05-18 浏览次数:21131 次
public static DataTable CreateExcelDataSource(string url) { DataTable dt = null; string connetionStr = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + url + ";" + "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"; string strSql = "select * from [Sheet1$]"; OleDbConnection oleConn = new OleDbConnection(connetionStr); OleDbDataAdapter oleAdapter = new OleDbDataAdapter(strSql, connetionStr); try { dt = new DataTable(); oleAdapter.Fill(dt); return dt; } catch (Exception ex) { throw ex; } finally { oleAdapter.Dispose(); oleConn.Close(); oleConn.Dispose(); } }
------解决方案--------------------
楼主的代码好非主流。。。
顶楼上的,只是楼上没考虑到excel表中第一张表名,不一定为sheet
------解决方案--------------------
这个是我代码使用是成功的,给你了,有问题我们在联系 ,qq497950652
public DataSet ExcelToDS(string filePath, string tableName)
{
// string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
//"HDR=Yes;" 这个参数说明第一行是列名,而不是数据. "HDR=No;"正好与前面的相反。
//"IMEX=1;" 告诉driver总是把数据作为text 类型.注意,这选项会影响excel的写访问(sheet write access negative)。
string fileExtension = Path.GetExtension(filePath);
String strConn="";
if (fileExtension.ToLower() == ".xls")
strConn = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
else if (fileExtension.ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= " + filePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES; IMEX=1\"";
else if (fileExtension.ToLower() == ".xlsb")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES ; IMEX=1\"";
else if (fileExtension.ToLower() == ".xlsm")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0 Macro;HDR=YES; IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
try
{
strExcel = string.Format(&qu