【问题标题】:Parsing CSV file with type使用类型解析 CSV 文件
【发布时间】:2012-02-25 19:19:58
【问题描述】:

我正在尝试解析 CSV 并从中构造一个 DataTable。现在棘手的部分是我想在构建数据表之前分配数据类型。 例如,考虑以下 CSV 文件

Name,Age,Salary
A,30,1000
B,35,1500
C,40,2000

我想在我正在构建的数据表中将 Name 存储为字符串,将 Age 存储为 Int,将 Salary 存储为十进制。关于最好的方法有什么建议吗?

【问题讨论】:

  • 程序如何区分30和1000,将前者视为int,将后者视为decimal?在提供一些其他信息之前,这无法完成。例如,列名和数据类型之间的映射。
  • 如果你可以使用 oledb。您可以使用 schema.ini 来定义列类型。检查这个stackoverflow.com/questions/8683180/…
  • 感谢 Shoaib。它按我想要的方式工作。 Schema.ini 就是答案。

标签: c# types csv datatable


【解决方案1】:

这是一个忽略大多数错误检查和一些良好编码实践的幼稚实现:

namespace StackOverflowConsole
{
    using System;
    using System.IO;
    using System.Data;

    class Program
    {
        static void Main(string[] args)
        {
            var path = @"C:\temp\test.csv";

            CreateTestFile(path);

            var dataTable = new DataTable();
            dataTable.Columns.Add("Name", typeof(string));
            dataTable.Columns.Add("Age", typeof(int));
            dataTable.Columns.Add("Salary", typeof(decimal));

            // TODO: add checks, exception handling
            using (var reader = new StreamReader(path))
            {
                // reads all lines into a single string
                var lines = reader.ReadToEnd().Split(new char[] { '\n' });

                if (lines.Length > 0)
                {
                    // you may wanna skip the first line, if you're using a file header
                    foreach (string line in lines)
                    {
                        if (string.IsNullOrWhiteSpace(line))
                        {
                            continue;
                        }

                        // split the current line using the separator
                        var tokens = line.Trim().Split(new char[] { ',' });

                        // check your assumptions on the CSV contents
                        // ex: only process lines with the correct number of fields
                        if (tokens.Length == 3)
                        {
                            var person = new Person();

                            person.Name = tokens[0];
                            // a better implementation would use TryParse()
                            person.Age = Int32.Parse(tokens[1]);
                            person.Salary = Decimal.Parse(tokens[2]);

                            dataTable.Rows.Add(person.Name, person.Age, person.Salary);
                        }
                    }
                }
            }
        }

        private static void CreateTestFile(string path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (var writer = new StreamWriter(path))
            {
                writer.WriteLine("A,30,1000");
                writer.WriteLine("B,35,1500");
                writer.WriteLine("C,40,2000");
            }
        }
    }

    public class Person
    {
        public string Name;
        public int Age;
        public decimal Salary;
    }
}

【讨论】:

    【解决方案2】:

    试试这个:

    将 CSV 文件保存在代码目录中

    string path = Server.MapPath("emp.csv");
                string header = "Yes";
                string sql = string.Empty;
                DataTable dt = null;
                string fullpath = Path.GetDirectoryName(path);
                string fileName = Path.GetFileName(path);
                OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullpath + ";Extended Properties=\"Text;HDR=" + header + "\"");
                OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + fileName + "]", connection);
                dt = new DataTable();
                dt.Columns.Add("Name", typeof(string));
                dt.Columns.Add("Age", typeof(int));
                dt.Columns.Add("Salary", typeof(decimal));
                da.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 2014-05-29
      • 2017-04-01
      • 1970-01-01
      • 2018-12-09
      • 2018-01-03
      相关资源
      最近更新 更多