我们习惯了直接连到数据库上面读取数据表的数据内容;
如果有一天我们需要读取CSV,EXCEL文件的内容的时候,可不可以也像读数据表的方式一样呢?当然可以,使用OleDB ADO.NET是很简单的事情
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static bool WriteContentToFile(FileStream fs, StringBuilder sb) 2 { 3 bool succ = false; 4 using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) 5 { 6 sw.WriteLine(sb.ToString()); 7 succ = true; 8 9 } 10 return succ; 11 }
按SQL的方式读取Excel文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static void ImportDictionaryFromExcel(string strExcelFileName,IList<Dictionary> list,bool Exce03Or07) 2 { 3 4 string oleDB = string.Empty; 5 6 if (Exce03Or07) 7 { 8 oleDB = "Jet.OLEDB.4.0"; 9 } 10 else 11 { 12 oleDB = "ACE.OLEDB.12.0"; 13 } 14 15 string strConn = string.Format("Provider=Microsoft.{0};Data Source={1};Extended Properties='Excel 8.0;HDR=YES;IMEX=1'", oleDB, strExcelFileName); 16 17 //string strExcel = string.Format("select * from [{0}$]", strSheetName); 这是一种方法 18 string strExcel = "select * from [sheet1$]"; 19 20 using (IDbConnection conn = new OleDbConnection(strConn)) 21 { 22 //适配到数据源 23 IDbDataAdapter adapter = new OleDbDataAdapter(strExcel, (OleDbConnection)conn); 24 DataSet ds = new DataSet(); 25 adapter.Fill(ds); 26 DataTable dt =ds.Tables[0]; 27 if (dt.Rows.Count > 0) 28 { 29 foreach (DataRow dr in dt.Rows) 30 { 31 string name=dr["Name"].ToString().Trim(); 32 string type=dr["Type"].ToString().Trim(); 33 string ripplesTo=dr["RipplesTo"].ToString().Trim(); 34 string engName=dr["ENGName"].ToString().Trim(); 35 string cnName=dr["CNName"].ToString().Trim(); 36 string meaning=dr["Meaning"].ToString().Trim(); 37 38 39 } 40 41 } 42 43 } 44 45 46 }