前提
在Windows下進行數據處理的時候最常見的情況莫過于讀取Microsoft的Excel文件了,Excel的普及率驚人,是事實上的標準。以前的開發中我采用調用第三方類庫 NPOI 的方式來處理Excel。這個方式有兩個缺點:
如果只是簡單的導入數據,完全可以有更加簡單的方案,方案的限制條件為;
依賴
還是有依賴的 2007 Office System Driver: Data Connectivity Components
如果沒有安裝Driver,你會得到以下的報錯:
Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
代碼
public static DataTable ReadAsTable(string xlsxFile, string sheetName = "Sheet1"){ var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=/"Excel 12.0;HDR=Yes;IMEX=1/"", xlsxFile); var adapter = new OleDbDataAdapter($"SELECT * FROM [{sheetName}$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, sheetName); return ds.Tables[sheetName];}在 connectionString 中有兩個Extended Properties可以根據需要進行修改:
技巧
有時候我們需要將讀取的數據綁定到特定類型上,我們可以這樣做:
var query = dt .AsEnumerable() .Where(x => x.Field<string>("phoneNumber") != string.Empty) .Select(x => new Contact { FirstName= x.Field<string>("First Name"), LastName = x.Field<string>("Last Name"), PhoneNumber =x.Field<string>("Phone Number"), });以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答