c#从txt读取数据填入datatable

时间:2022-11-06 11:37:49
从TXT读取并存入到DataTable
从TXT读取并存入到DataTable的代码,以逗号为分割符,TXT中的数据例如:
————————
1,105.64,38.65
2,106.05,38.72
————————

        static void Main(string[] args)
        {
            #region 读取字符串

            StreamReader sr = new StreamReader("c:\\bb.txt", Encoding.GetEncoding("GB2312"));
            string txt = sr.ReadToEnd().Replace("\r\n","-");
            string[] nodes = txt.Split('-');

            #endregion

            #region 填充DataTable

            DataTable dt = new DataTable();

            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Field1", typeof(double));
            dt.Columns.Add("Field2", typeof(double));

            foreach (string node in nodes)
            {
                string[] strs = node.Split(',');
                DataRow dr = dt.NewRow();
                dr["ID"] = strs[0];
                dr["Field1"] = strs[1];
                dr["Field2"] = strs[2];

                dt.Rows.Add(dr);
            }

            #endregion
            sr.Close();

        }


------解决方案--------------------
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("经度", typeof(double));
dt.Columns.Add("纬度", typeof(double));
string[] rows = File.ReadAllLines(@"c\test.txt"));
foreach (string row in rows)
dt.Rows.Add(row.Split(','));
dataGridView1.DataSource = dt;