使用类型解析CSV文件

时间:2012-02-03 05:35:18

标签: c# types csv datatable

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

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

我想在我构建的数据表中将Name存储为字符串,Age as Int和Salary as decimal。有关最佳方法的任何建议吗?

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

试试这个:

将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();