转载自:
NET 讀取Excel 2007的xlsx文件和讀取老的.xls文件是一樣的,都是用Oledb讀取,僅僅連接字符串不同而已。
讀取xlsx 用的是Microsoft.Ace.OleDb.12.0;具體操作方法如下:public static DataTable GetExcelToDataTableBySheet(string FileFullPath, string SheetName)
{ //string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + FileFullPath + ";Extended Properties='Excel 8.0; HDR=NO; IMEX=1'"; //此連接只能操作Excel2007之前(.xls)文件string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + FileFullPath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; //此連接可以操作.xls與.xlsx文件OleDbConnection conn = new OleDbConnection(strConn);conn.Open();DataSet ds = new DataSet();OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", SheetName), conn); //("select * from [Sheet1$]", conn);odda.Fill(ds, SheetName);conn.Close();return ds.Tables[0];}
讀取Excel文件時,可能一個文件中會有多個Sheet,因此獲取Sheet的名稱是非常有用的。具體操作方法如下:
//根據Excel物理路徑獲取Excel文件中所有表名
public static String[] GetExcelSheetNames(string excelFile)
{ OleDbConnection objConn = null;System.Data.DataTable dt = null;try
{ //string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + excelFile + ";Extended Properties='Excel 8.0; HDR=NO; IMEX=1'"; //此連接只能操作Excel2007之前(.xls)文件string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + excelFile + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; //此連接可以操作.xls與.xlsx文件
objConn = new OleDbConnection(strConn);objConn.Open();dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);if (dt == null){ return null;}String[] excelSheets = new String[dt.Rows.Count];int i = 0;foreach (DataRow row in dt.Rows){ excelSheets[i] = row["TABLE_NAME"].ToString();i++;}return excelSheets;
}catch{ return null;}finally{ if (objConn != null){ objConn.Close();objConn.Dispose();}if (dt != null){ dt.Dispose();}}}