C# 读取CSV格式数据 读取为DataTable类型

2021-04-20 08:28

阅读:617

标签:url   def   pen   cat   text   name   hdr   return   pos   

先贴代码:

using System.Data;
using System.Data.OleDb;

 static void Main(string[] args)
        {
            var strpath = System.Environment.CurrentDirectory + "\\";
            var filename = "ss.csv";
            DataSet dataset = GetCsvData(strpath, filename);
            if (dataset.Tables.Count > 0)
            {
                foreach (DataTable itemTable in dataset.Tables)
                {
                    string table_sheetName=itemTable.TableName;//

                    DataTable datNew = itemTable.DefaultView.ToTable(false, new string[] {//选择列
                        "列名","ProjectName"
                    });
                }
            }
        }


        static DataSet GetCsvData(string fileNameUrl, string fileName)
        {
            OleDbConnection OleCon = new OleDbConnection();
            OleDbCommand OleCmd = new OleDbCommand();
            OleDbDataAdapter OleDa = new OleDbDataAdapter();

            DataSet csvData = new DataSet();
            OleCon.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileNameUrl +
                ";Extended Properties=‘Text;FMT=Delimited;HDR=YES;‘";
            OleCon.Open();
            OleCmd.Connection = OleCon;
            OleCmd.CommandText = "select * From " + fileName;
            OleDa.SelectCommand = OleCmd;
            try
            {
                OleDa.Fill(csvData, "CsvFileVCQData");
                return csvData;
            }
            catch
            {
                return csvData;
            }
            finally
            {
                OleCon.Close();
                OleCmd.Dispose();
                OleDa.Dispose();
                OleCon.Dispose();
            }
        }

 

C# 读取CSV格式数据 读取为DataTable类型

标签:url   def   pen   cat   text   name   hdr   return   pos   

原文地址:https://www.cnblogs.com/yangsirc/p/8624005.html


评论


亲,登录后才可以留言!