c# Datatable (三)读写txt文件

该代码片段展示了如何使用C#读取UTF-8或GB2312编码的txt文件,逐行解析,然后将数据填充到DataTable中,处理可能的数据清洗和格式转换。

一、读txt文件到Datatable

public static DataTable read_txt_file(string file_path_all)
{
    // 注册编码
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

    #region 读取本地文件
    //Ftp_State.ftp_downloadFile(file_path_all, dt_lcd, "", "");
    //string text = File.ReadAllText(file_path_all);
    //Console.WriteLine(text);

    DataTable dt_lcd = new DataTable();
    //dt_lcd = ReadTXT(file_path_all);
    //DataSet_Deal.print_DT(dt_lcd);

    //string path = file_path_all;
    //// 声明一个utf-8编码对象
    //UTF8Encoding utf8 = new UTF8Encoding();
    //// 以行为单位读取所有文本文件内容,再赋值给一个字符串数组
    //string[] contents = File.ReadAllLines(path, utf8);
    ////或者 
    //string[] contents2 = File.ReadAllLines(path, Encoding.UTF8);
    ////或者,这种方式写的是编码原名称,上面写的由于命名规则,有的
    //string[] contents3 = File.ReadAllLines(path, Encoding.GetEncoding("UTF-8"));
    //for (int i = 0; i < contents.Length; i++)
    //{
    //    Console.WriteLine(contents[i]);
    //}

    try
    {
        //string[] lines = File.ReadAllLines(file_path_all, Encoding.GetEncoding("UTF-8"));
        //string[] lines = File.ReadAllLines(file_path_all, Encoding.ASCII);
        string[] lines = File.ReadAllLines(file_path_all, Encoding.GetEncoding("GB2312"));//ANSI


        int txt_row = 0;
        string line_str;
        int column_start = 0;
        string[] split;

        //遍历行
        foreach (string line in lines)
        {
            //if (txt_row == 50) break;

            //Trim()删除字符串头部及尾部出现的空格,删除的过程为从外到内,直到碰到⼀个⾮空格的字符为⽌,所以不管前后有多少个连续的空格都会被删除掉。
            if ((line.Trim() != string.Empty) & line.FirstOrDefault() != '-')
            {
                Console.WriteLine("txt_row=" + txt_row);
                //line_str=line.Trim();
                //line_str = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(line.Trim(), "\t");

                split = line.Split('\t');//\t
                                         //line = line.Trim();
                Console.WriteLine("line=" + line);
                //split = line.Split(' ');//\t

                txt_row++;

                //将每一行添加到新的DataTable中
                DataRow dr = dt_lcd.NewRow();

                if (txt_row == 1)//设置列名
                {
                    //设置列名
                    for (int txt_column = column_start; txt_column < split.Length; txt_column++)
                    {
                        //设置表格列名
                        string clm_name = split[txt_column].Trim();
                        //clm_name = clm_name.Replace("/", "_");
                        //clm_name = clm_name.Replace("-", "_");
                        //clm_name = clm_name.Replace("(", "_");
                        //clm_name = clm_name.Replace(" ", "_");
                        //clm_name = clm_name.Replace("%", "_");
                        //clm_name = clm_name.Replace(")", "");
                        //if (clm_name.ToUpper() == "START" || clm_name.ToUpper() == "MODIFY") clm_name = clm_name + "_DATE";

                        Console.WriteLine("clm_name = " + clm_name);

                        //dt_lcd.Columns.Add("Column1");
                        //将列名加入到表中
                        if(clm_name!="") dt_lcd.Columns.Add(new DataColumn(clm_name.ToUpper(), typeof(string)));
                    }
                }
                else
                {
                    //Console.WriteLine("dt_lcd.Columns.Count=" + dt_lcd.Columns.Count);
                    for (int txt_column = column_start; txt_column < dt_lcd.Columns.Count; txt_column++)
                    {
                        //Console.WriteLine(dt_lcd.Columns[txt_column].ColumnName);
                        //Console.WriteLine("txt_column=" + txt_column);
                        //Console.WriteLine("split[txt_column].Trim()=" + split[txt_column].Trim());
                        dr[dt_lcd.Columns[txt_column].ColumnName] = split[txt_column].Trim();

                    }
                    dt_lcd.Rows.Add(dr);
                }
                //if (txt_row != 1) 

                //DataRow row = dt_lcd.NewRow();
            }
        }

        #endregion

        for (int row = 0; row < dt_lcd.Rows.Count; row++)
        {
            for (int clm = 0; clm < dt_lcd.Columns.Count; clm++)
            {
                dt_lcd.Rows[row][clm] = Tools.check_number(dt_lcd.Rows[row][clm].ToString());//数字删除逗号

                if (dt_lcd.Rows[row][clm].ToString() == "?")
                {
                    dt_lcd.Rows[row][clm] = "";
                }

                if (dt_lcd.Rows[row][clm].ToString().Contains(','))
                {
                    dt_lcd.Rows[row][clm] = dt_lcd.Rows[row][clm].ToString().Replace(",", ",");
                }
            }
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine("ERROR = " + ex);
    }
    return dt_lcd;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝丶曦月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值