1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C# 读取CSV和EXCEL文件示例

C# 读取CSV和EXCEL文件示例

时间:2020-10-03 14:39:17

相关推荐

C# 读取CSV和EXCEL文件示例

我们习惯了直接连到数据库上面读取数据表的数据内容;

如果有一天我们需要读取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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。
相关阅读
C# 读取CSV文件

C# 读取CSV文件

2021-03-05

php 读取CSV文件示例

php 读取CSV文件示例

2020-12-16

c++读取csv文件示例

c++读取csv文件示例

2020-06-23

c#读取CSV格式文件

c#读取CSV格式文件

2019-11-04