我在允许用户从 CSV 文件导入订单的程序中使用 LINQtoCSV。我的所有代码都在工作,但是,如果 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 文件没有确切的标题,它将无法工作。我实际上只需要的数据是前 4 个字符串。
下面是我实际读取数据的函数。
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 中是否有可能