允许用户选择要导入的列标题

时间:2018-10-30 10:50:44

标签: c# linq csv linqtocsv

我在程序中使用LINQtoCSV,该程序允许用户从CSV文件导入订单。我可以使用所有代码,但是,如果CSV文件没有确切的列标题,那么它将无法正常工作。

下面是LINQtoCSV读到的我的课程-

public class orderProduct
{
    public orderProduct() { }
    public string product { get; set; }
    public string price { get; set; }
    public string orderQty { get; set; }
    public string value { get; set; }

    public string calculateValue()
    {
        return (Convert.ToDouble(price) * Convert.ToDouble(orderQty)).ToString();
    }
}

如果CSV文件没有确切的标题,它将无法使用。我实际上只需要前四个字符串。

下面是我实际读取数据的函数。

private void csvParse()
{
    // order.Clear();
    string fileName = txt_filePath.Text.ToString().Trim();

    try
    {
        CsvContext cc = new CsvContext();

        CsvFileDescription inputFileDescription = new CsvFileDescription
        {
            SeparatorChar = ',',
            FirstLineHasColumnNames = true
        };

        IEnumerable<orderProduct> fromCSV = cc.Read<orderProduct>(fileName, inputFileDescription);

        foreach (var d in fromCSV)
        {
            MessageBox.Show($@"Product:{d.product},Quantity:""{d.orderQty}"",Price:""{d.price}""");
            orderReturn.Add(d);                
        }
        this.DialogResult = DialogResult.Yes;
        this.Close();
    }
    catch (Exception ex)
    {
        if (ex.ToString().Contains("being used by another process"))
        {
            MessageBox.Show("Error: Please close the file in Excel and try again");
        }
        else
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

我希望用户能够仅传递文件,然后选择与相应值相关的相关列,然后忽略未选择的任何列而读入数据。

希望这一切都有道理,这在LINQtoCSV中是可能的

1 个答案:

答案 0 :(得分:1)

您必须将IgnoreUnknownColumns = true添加到您的CsvFileDescription

CSV:

product,price,someColumn,orderQty,value,otherColumn
my product,$123,xx,2,$246,aa
my other product,$10,yy,3,$30,bb

工作代码(我对您的代码做了一些修改,以便在控制台中运行)

using System;
using System.Collections.Generic;
using LINQtoCSV;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            csvParse();
            Console.ReadLine();
        }

        private static void csvParse()
        {
            string fileName = "../../../test.csv"; // provide a valid path to the file

            CsvContext cc = new CsvContext();

            CsvFileDescription inputFileDescription = new CsvFileDescription
            {
                SeparatorChar = ',',
                FirstLineHasColumnNames = true,
                IgnoreUnknownColumns = true // add this line
            };

            IEnumerable<orderProduct> fromCSV = cc.Read<orderProduct>(fileName, inputFileDescription);

            foreach (var d in fromCSV)
            {
                Console.WriteLine($@"Product:{d.product},Quantity:""{d.orderQty}"",Price:""{d.price}""");
            }
        }
    }

    public class orderProduct
    {
        public orderProduct() { }
        public string product { get; set; }
        public string price { get; set; }
        public string orderQty { get; set; }
        public string value { get; set; }

        public string calculateValue()
        {
            return (Convert.ToDouble(price) * Convert.ToDouble(orderQty)).ToString();
        }
    }
}

输出:

Product:my product,Quantity:"2",Price:"$123"
Product:my other product,Quantity:"3",Price:"$10"

如果属性的名称与CSV列的名称不同,则应使用CsvColumn属性:

public class OrderProduct
{
    [CsvColumn(Name = "product")]
    public string Product { get; set; }

    [CsvColumn(Name = "price")]
    public string Price { get; set; }

    [CsvColumn(Name = "orderQty")]
    public string OrderQuantity { get; set; }

    public string Value { get; set; }

    public string calculateValue()
    {
        return (Convert.ToDouble(Price) * Convert.ToDouble(OrderQuantity)).ToString();
    }
}

或者,如果您希望按列索引映射列:

public class OrderProduct
{
    [CsvColumn(FieldIndex = 0)]
    public string Product { get; set; }

    [CsvColumn(FieldIndex = 1)]
    public string Price { get; set; }

    [CsvColumn(FieldIndex = 2)]
    public string OrderQuantity { get; set; }

    public string Value { get; set; }

    public string calculateValue()
    {
        return (Convert.ToDouble(Price) * Convert.ToDouble(OrderQuantity)).ToString();
    }
}

如果必须动态指定列,唯一的方法似乎是读取原始数据并自行处理(解决方案基于this article):

internal class DataRow : List<DataRowItem>, IDataRow
{
}
...
int productColumnIndex = 0; // your users will provide it
var fromCSV = cc.Read<DataRow>(fileName);
foreach (var row in fromCSV)
{
    var orderProduct = new OrderProduct
    {
        Product = row[productColumnIndex].Value,
    };

    Console.WriteLine(orderProduct.Product);
}