C# 讀取CSV和EXCEL文件示例

咱們習慣了直接連到數據庫上面讀取數據表的數據內容;數據庫

若是有一天咱們須要讀取CSV,EXCEL文件的內容的時候,可不能夠也像讀數據表的方式同樣呢?固然能夠,使用OleDB ADO.NET是很簡單的事情ide

 

 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         }
WriteContentToFile

按SQL的方式讀取Excel文件ui

 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         }
ImportDictionaryFromExcel
相關文章
相關標籤/搜索