代码改变世界

c# 格式化文本txt,csv的指定列

2012-12-06 12:48  小sa  阅读(582)  评论(0编辑  收藏  举报
从文本文件csv,txt 等文件内读出指定列方法多种现用微软自带的 ODBC桥接方式读取指定列。

 public static System.Data.DataSet LoadTxtFile(int numberOfRows)
        {
            System.Data.DataSet ds = new System.Data.DataSet();
            //try
            //{
            // Creates and opens an ODBC connection
            string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=D:\\;Extensions=asc,csv,tab,txt;Persist Security Info=False; HDR = YES;FMT = TabDelimiter"; 
            //string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=D:\\;Extensions=asc,csv,tab,txt;Persist Security Info=False; HDR = NO;FMT = Delimited(|)"; 
            
            string sql_select;
            //string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataSourcePath + @";Extended Properties=""text;HDR=NO;FMT=TabDelimiter""";  
            using (System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(strConnString.Trim()))
            {
                conn.Open();
                sql_select = "select top " + 10 + " * from [A3.txt]";
                //Creates the data adapter
                System.Data.Odbc.OdbcDataAdapter obj_oledb_da = new System.Data.Odbc.OdbcDataAdapter(sql_select, conn);

                //Fills dataset with the records from CSV file
                obj_oledb_da.Fill(ds, "TB");
                System.Data.DataView view = new System.Data.DataView(ds.Tables[0]);
                //closes the connection
                System.Data.DataTable dt = view.ToTable(true, "COLUMN9", "COLUMN0", "COLUMN1");
                conn.Close();
            }
            return ds;

        }

 


TabDelimiter 为\t制表符 也可以是其他的 如,|等分隔符 若本机注册表内默认分隔符为 Delimited(|)需要改注册表内指定值

当然也可直接用StreamReader读指定行指定列暂不做补充