自动识别2003和2007文件并读取到dataset,加入了读取工作表名称的方法,修正了因修改工作表名称而不能正确读取的错误。
如出现此错误信息:未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序。
public static DataSet ReadExcel_ds(string FilePath, string companycd) { string subfile = FilePath.Substring(FilePath.LastIndexOf(".") + 1); DataSet ds = new DataSet(); string strCon = ""; if (subfile.ToUpper() == "XLS") { strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + FilePath; } if (subfile.ToUpper() == "XLSX")//excel2007读取 { strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0;HDR=YES\""; } System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon); //string strCom = "SELECT * FROM [Sheet1$]"; Conn.Open(); System.Data.DataTable sTable = Conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);//新添加 2010-10-14 string tableName = sTable.Rows[0][2].ToString().Trim();//新添加 2010-10-14 获取工作表名称 string strCom = "SELECT * FROM [" + tableName + "]"; System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn); myCommand.Fill(ds, "[" + tableName + "]"); Conn.Close(); return ds; }