我正在尝试将包含以下数据的CSV文件存储到列表中:
我有以下代码将CSV成功保存到App_Data文件夹:
public static IEnumerable<Product> CSVProducts;
public static IEnumerable<Product> CSVToList(HttpPostedFileBase CSVFile)
{
if (CSVFile == null || CSVFile.ContentLength == 0)
{
throw new InvalidOperationException("No file has been selected for upload or the file is empty.");
}
// saves the file into a directory in the App_Data folder
var fileName = Path.GetFileName(CSVFile.FileName);
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName);
CSVFile.SaveAs(path);
CSVProducts = from line in File.ReadAllLines(path).Skip(1)
let columns = line.Split(',')
select new Product
{
Id = int.Parse(columns[0]),
Barcode = columns[13],
Name = columns[1],
CategoryName = columns[9],
Description = columns[2],
Price = int.Parse(columns[4])
};
return CSVProducts;
}
但是,获取列表的LINQ查询会显示以下错误消息:
Input string was not in a correct format.
Source Error:
Line 31: CSVProducts = from line in File.ReadAllLines(path).Skip(1)
Line 32: let columns = line.Split(',')
Line 33: select new Product
Line 34: {
Line 35: Id = int.Parse(columns[0]),
Source File: C:\Users\Documents\Visual Studio 2015\Projects\Website\Models\Repository.cs
Line: 33
当我在Visual Studio中调试时,我无法查看LINQ查询中变量内部的内容,但我可以看到CSVProducts和&#39; Current&#39;它的属性值为null。
这是产品和类别的类:
public class Product
{
public int Id { get; set; }
public string Barcode { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[Required]
public Byte[] Image { get; set; }
[Required]
public Decimal Price { get; set; }
[Required]
public bool ShowOnIndex { get; set; }
}
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public Byte[] Image { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
答案 0 :(得分:1)
谢谢你们在评论部分。
LINQ查询给出该错误的原因是因为Product类中Price属性的数据类型为Decimal
。我最初是在查询中解析价格值Int
:Price = int.Parse(columns[4])
。
我将其更改为Price = decimal.Parse(columns[4])
,现在LINQ查询成功解析Excel CSV文件,并将每条记录存储在IEnumerable产品列表中。再次感谢你们。爱你们。 :)