输入字符串解析CSV不是文件格式正确
问题描述:
我想存储包含以下数据列表的CSV文件:输入字符串解析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内部的内容以及“Current”属性的值为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; }
}
答
谢谢你们在评论部分。
LINQ查询给出该错误的原因是因为Product类中Price属性的数据类型为Decimal
。我最初是在价格查询中解析Int
:Price = int.Parse(columns[4])
。
我将其更改为Price = decimal.Parse(columns[4])
,现在LINQ查询成功解析了Excel CSV文件,并将每条记录存储在IEnumerable产品列表中。再次感谢你们。爱你们。 :)
错误发生时'columns [0]'的值是什么? – David
它看起来像'columns [0]'是ProductID? – IAbstract
这基本上是一个解析问题。根据你的代码,你正在解析两列,这是0和4.请检查这些值。它有一些非数字字符。 – Kalyan