C#讀取Excel表格中資料並返回datatable
阿新 • • 發佈:2019-02-01
在軟體開發的過程中,經常用到從excel表格中讀取資料作為資料來源,以下整理了一個有效的讀取excel表格的方法。
DataTable GetDataTable(string tableName,string leftTopCel,string rightbutCel) { bool hasTitle = false; OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "Excel(*.xlsx;*.xls)|*.xlsx;*.xls|所有檔案(*.*)|*.*"; openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); openFile.Multiselect = false; if (openFile.ShowDialog() == DialogResult.Cancel) return null; var filePath = openFile.FileName; string fileType = System.IO.Path.GetExtension(filePath); if (string.IsNullOrEmpty(fileType)) return null; using (DataSet ds = new DataSet()) { string strCon = string.Format("Provider=Microsoft.Jet.OLEDB.{0}.0;" + "Extended Properties=\"Excel {1}.0;HDR={2};IMEX=1;\";" + "data source={3};", (fileType == ".xls" ? 4 : 12), (fileType == ".xls" ? 8 : 12), (hasTitle ? "Yes" : "NO"), filePath); string strCom = " SELECT * FROM [" + tableName + "$" + leftTopCel + ":" + rightbutCel + "] "; using (OleDbConnection myConn = new OleDbConnection(strCon)) using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn)) { myConn.Open(); myCommand.Fill(ds); } if (ds == null || ds.Tables.Count <= 0) return null; return ds.Tables[0]; } }
tableName是該表表格的名稱 如:Sheet1
leftTopCel是左上角單元格名稱,如:A1
rightbutCel是右上角單元格名稱,如:B13
同時需要引入名稱空間
using System.Data;
using System.Data.OleDb;
理論上,該方法支援所有excel表格,但是在實際的使用過程中,我們發現,這隻支援xls格式的,所以如果對xlsx的檔案如果開啟失敗的話,可以嘗試把xlsx檔案另存問xls格式,再重新開啟。