原文地址:http://www.open-open.com/code/view/1420029490093
public DataTable ExcelToDS(string Path) { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); string strTable = ""; if (schemaTable.Rows.Count > 0) { strTable = schemaTable.Rows[0]["TABLE_NAME"].ToString(); } string strExcel = ""; OleDbDataAdapter myCommand = null; DataSet ds = null; strExcel = "select * from [" + strTable + "]"; myCommand = new OleDbDataAdapter(strExcel, strConn); ds = new DataSet(); myCommand.Fill(ds, "table1"); conn.Close(); return ds.Tables[0]; }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string strFilePath = Server.MapPath("~") + "upload\\bool.xls"; ExcelToDS(strFilePath); } }
在导出Excel的过程中,有可能出现的问题:OleDbConnection.open() 外部表不是预期的格式
很多人换了2010后,问的最多的问题之一是2003里最经典的ADO中的“provider=Microsoft.Jet.OLEDB.4.0”这句怎么不能用了。
百度一下可以了解到,Microsoft.Jet.OLEDB.4.0是Microsoft Jet引擎,这适用于2003版本(2003之前的我没装,所以也不知道能向下适应到哪个版本),而在2007中,微软对其旗下 Access 与 Excel 的主要文件格式进行修改,并且重命名为 .accdb(Access 2007 数据库文件)与 .xlsx(Excel 2007 文件),因此未被 Microsoft Jet 引擎所支持,不过微软也很快的提出了Microsoft Office 2007 Desktop Drivers: Data Connectivity Components 来支持,目前的解决方法就是把连接字符串中的数据提供者改为Microsoft.ACE.OLEDB.12.0。
//2003(Microsoft.Jet.Oledb.4.0)
string strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", excelFilePath);
//2010(Microsoft.ACE.OLEDB.12.0)
string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", excelFilePath);
若是乱码,我这边测试是不会提示这个错误的,可以成功导入。