1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > c#读取CSV格式文件

c#读取CSV格式文件

时间:2020-06-14 19:58:58

相关推荐

c#读取CSV格式文件

using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Text;using System.Threading.Tasks;namespace XXG{class CSVReader{static public bool readCSV(string filePath, out DataTable dt)//从csv读取数据返回table{dt = new DataTable(); try{System.Text.Encoding encoding = Encoding.Default;//GetType(filePath); //// DataTable dt = new DataTable();System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open,System.IO.FileAccess.Read);System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding);//记录每次读取的一行记录string strLine = "";//记录每行记录中的各字段内容string[] aryLine = null;string[] tableHead = null;//标示列数int columnCount = 0;//标示是否是读取的第一行bool IsFirst = true;//逐行读取CSV中的数据while ((strLine = sr.ReadLine()) != null){if (IsFirst == true){tableHead = strLine.Split(',');IsFirst = false;columnCount = tableHead.Length;//创建列for (int i = 0; i < columnCount; i++){DataColumn dc = new DataColumn(tableHead[i]);dt.Columns.Add(dc);}}else{aryLine = strLine.Split(',');DataRow dr = dt.NewRow();for (int j = 0; j < columnCount; j++){dr[j] = aryLine[j];}dt.Rows.Add(dr);}}if (aryLine != null && aryLine.Length > 0){dt.DefaultView.Sort = tableHead[0] + " " + "asc";}sr.Close();fs.Close();return true;}catch (Exception){return false;}}}}

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