我正在编写一个程序,使用的组合框是从csv文件填充,我最初只是使用streamreader来填充组合框,但我被指示使用gembox电子表格来填充它代替。
下面是我使用的流阅读器代码:
private static List<ItemLine> Readfile(string fileName, string defaultValueDescription)
{
string path = $".\\Backend Files\\{fileName}";
var items = new List<ItemLine>();
int row = 0;
//read the file
StreamReader reader = new StreamReader(path);
while (reader.EndOfStream == false)
{
string lines = reader.ReadLine();
row++;
if (row == 1)
{
items.Add(new ItemLine { Description = defaultValueDescription, Quantity = 0 });
continue;
}
string[] itemFields = lines.Split(",");
ItemLine IL = new ItemLine();
if (itemFields.Length == 2)
{
IL.Description = itemFields[0];
IL.Quantity = 0;
if (int.TryParse(itemFields[1], out int qty))
{
IL.Quantity = qty;
}
}
else if (itemFields.Length >= 3)
{
IL.Plan = itemFields[0];
IL.Description = itemFields[1];
IL.Quantity = 0;
if (int.TryParse(itemFields[2], out int qty))
{
IL.Quantity = qty;
}
}
///Add Items to List
items.Add(IL);
}
reader.Close();
return items;
}
这里是一个例子,我用gembox电子表格在我的程序的另一部分,我用它来更新csv文件,我想我试图弄清楚的代码看起来像:
public void updateFile(string filename, int range, ItemLine selectedItem, decimal outValue)
{
var fullPath = $".\\Backend Files\\{filename}";
SpreadsheetInfo.SetLicense("FREE -LIMITED-KEY");
var workbook = ExcelFile.Load(fullPath, new CsvLoadOptions(CsvType.CommaDelimited));
var worksheet = workbook.Worksheets[0];
for (int i = 1; i <= range; i++)
{
var plan = worksheet.Rows[i].Cells[0].Value;
var desc = worksheet.Rows[i].Cells[1].Value;
var csvDescription = plan + " - " + desc;
var platedescription = plan + " - ";
if (selectedItem.ComboDescription == csvDescription)
{
worksheet.Rows[i].Cells[2].Value = outValue;
}
if (selectedItem.plateDescription == platedescription)
{
worksheet.Rows[i].Cells[1].Value = outValue;
}
}
workbook.Save(fullPath, new CsvSaveOptions(CsvType.CommaDelimited));
}
1条答案
按热度按时间n7taea2i1#
试试这个:
另外,我不确定
defaultValueDescription
的逻辑,似乎在您的StreamReader
方法中,您只是因为它而跳过了CSV中的第一行。如果这是预期的行为,则从System.linq添加
.Skip(1)
扩展方法,如下所示: