类别:程序开发

日期:2021-08-26 浏览:2391 评论:0

看了很多txt转DataTable的,但是都没啥效果,自己写了一个
实现的效果是:每一列数据为一列DataColumn DataTable表头中含有字段名。

  public DataTable TXT2DataTable(string path)
        {
            try
            {
                StreamReader sR = File.OpenText(path);
                DataTable dt = new DataTable();
                string firstLine = sR.ReadLine();
                string[] colName = firstLine.Split('\t');
                foreach (var i in colName)
                {
                    DataColumn col = dt.Columns.Add(i.ToString());
                }
                string nextLine;
                while ((nextLine = sR.ReadLine()) != null)
                {
                    string[] every_row = nextLine.Split('\t');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        dr[i] = every_row[i];
                    }
                    dt.Rows.Add(dr);
                }
                sR.Close();
                return dt;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("数据格式错误!","提示:",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                return null;
            }


本文标题:C# txt文本转DataTable
本文链接:https://vtzw.com/post/752.html
作者授权:除特别说明外,本文由 零一 原创编译并授权 零一的世界 刊载发布。
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。
 您阅读本篇文章共花了: 

 可能感兴趣的文章

评论区

发表评论 / 取消回复

必填

选填

选填

◎欢迎讨论,请在这里发表您的看法及观点。