简体   繁体   English

如何在C#,MVC中将CSV转换为数据表

[英]How to convert csv to datatable in c#, mvc

I'm converting .csv file to datatable like below. 我正在将.csv文件转换为如下所示的数据表。

string header = isFirstRowHeader ? "Yes" : "No";
            string itinerarycsvfilePath = Path.GetDirectoryName(@"D:\projects\MSC cruise\MSCCruiseProjects\MsccruiseWithLogin\MsccruiseWithLogin\UnzippedFiles\itinff_gbr_eng.csv");
            string filename = Path.GetFileName(@"D:\projects\MSC cruise\MSCCruiseProjects\MsccruiseWithLogin\MsccruiseWithLogin\UnzippedFiles\itinff_gbr_eng.csv");
            string sql = @"SELECT * FROM [" + filename + "]";

            using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + itinerarycsvfilePath +
              ";Extended Properties=\"Text;HDR=" + header + "\""))
            using (OleDbCommand command = new OleDbCommand(sql, connection))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
            {
                DataTable dataTable = new DataTable("ItineraryDetails");
                dataTable.Locale = CultureInfo.CurrentCulture;
                adapter.Fill(dataTable);
                return dataTable;
            }

then the result when I look with quick watch 然后当我快速观看时的结果 在此处输入图片说明

  • Am I doing something wrong.I feel like that because table does not show like columns. 我做错什么了吗 what can I do for that. 我该怎么办。 hope your help. 希望你的帮助。

See code below 见下面的代码

    public class CSVReader
    {

        public DataSet ReadCSVFile(string fullPath, bool headerRow)
        {

            string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
            string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
            DataSet ds = new DataSet();

            try
            {
                if (File.Exists(fullPath))
                {
                    string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
                    string SQL = string.Format("SELECT * FROM {0}", filename);
                    OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
                    adapter.Fill(ds, "TextFile");
                    ds.Tables[0].TableName = "Table1";
                }
                foreach (DataColumn col in ds.Tables["Table1"].Columns)
                {
                    col.ColumnName = col.ColumnName.Replace(" ", "_");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return ds;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM