C# 微软提供的 csv文件解析工具类 非常方便

从老外的项目里看到的一个类库, 非常方便就记录下来了.

主要的类是 Microsoft.VisualBasic.FileIO.TextFieldParser

 private IEnumerable<Customer> LoadCustomerList(string fileName)
        {
            List<Customer> customerList = new List<Customer>();

            using (TextFieldParser parser = new TextFieldParser(fileName))
            {
                parser.Delimiters = new string[] { "," };
                parser.HasFieldsEnclosedInQuotes = true;

                string[] fields;
                while ((fields = parser.ReadFields()) != null)
                {
                    Customer customer = new Customer();
                    customer.CustomerID = int.Parse(fields[0]);
                    customer.FirstName = fields[1];
                    customer.LastName = fields[2];
                    customer.EmailAddress = fields[3];
                    customer.Phone = fields[4];
                    customer.City = fields[5];
                    customer.StateProvince = fields[6];
                    customer.PostalCode = fields[7];
                    customer.NumOrders = int.Parse(fields[8]);

                    customerList.Add(customer);
                }
            }

            return customerList;
        }

猜你喜欢

转载自blog.csdn.net/phker/article/details/79108042