我们习惯了直接连到数据库上面读取数据表的数据内容;
如果有一天我们需要读取CSV,EXCEL文件的内容的时候,可不可以也像读数据表的方式一样呢?当然可以,使用OleDB 是很简单的事情
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文件
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 else11 {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 {31string name=dr["Name"].ToString().Trim();32string type=dr["Type"].ToString().Trim();33string ripplesTo=dr["RipplesTo"].ToString().Trim();34string engName=dr["ENGName"].ToString().Trim();35string cnName=dr["CNName"].ToString().Trim();36string meaning=dr["Meaning"].ToString().Trim();37 3839 }40 41 }42 43 }44 45 46 }
ImportDictionaryFromExcel