【发布时间】:2011-02-23 15:59:42
【问题描述】:
我有一个实际上不循环的循环问题。我在下面发布了我的代码的简化版本。基本上,使用 NPOI excel 库,我有一个 excel 文件,其中包含第一张和第二张工作表上的数据,所以我需要做一个循环来通过两个工作表。
以下是我到目前为止所做的,但这仅适用于第一张纸然后退出。它无法增加变量 w。如您所见,此代码中还实现了其他循环,它们运行良好,所以我不明白。
这是漫长的一天,也许我错过了一些非常简单的事情。我可能把它放错了或什么的。如果其他人能发现我可能做错了什么,我将不胜感激:)
public class SalesFileProcessor : ISalesProcessor
{
public List<FTPSalesRow> ProcessSalesFile(string filename)
{
try
{
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read))
{
int numberOfSheets = 2;
//Loop through sheets - does not work
for (int w = 0; w <= numberOfSheets; w++)
{
HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs);
HSSFSheet sheet = templateWorkbook.GetSheetAt(w);
HSSFRow row = null;
for (int i = 1; i <= sheet.LastRowNum; i++)
{
FTPSalesDetails t = null;
int currentColumn = 0;
try
{
ModelContainer ctn = new ModelContainer();
row = sheet.GetRow(i);
if (row == null)
{
continue;
}
t = new FTPSalesDetails
{
RowNumber = i,
InvoiceDate = GetCellValue(row.GetCell(0)),
CountrySoldIn = GetCellValue(row.GetCell(1)),
NetUnitsSold = GetCellValue(row.GetCell(2)),
Item = GetCellValue(row.GetCell(3)),
ProductCode = GetCellValue(row.GetCell(5)),
};
if (t.ProductCode == null && t.NetUnitsSold == null)
{
return null;
}
int Qty = int.Parse(t.NetUnitsSold);
for (int x = 0; x < Qty; x++)
{
ItemSale ts = new ItemSale
{
ItemID = GetItemID(t.ProductCode),
ManufacturerID = GetManufacturerID("Samsung"),
DateSold = DateTime.Now,
};
ctn.AddToItemSales(ts);
ctn.SaveChanges();
}
}
catch (IndexOutOfRangeException) { }
}
} //End Loop - the one that doesn't work
}
}
catch (IOException exp)
{
throw new FTPSalesFileProcessingException("Could not open the Sales data file", exp);
}
catch (Exception exp)
{
throw new FTPSalesFileProcessingException("An unknown eror occured during processing the file", exp);
}
return null;
}
【问题讨论】:
-
你试过调试吗?看我和w? :)
-
@Armen,我当然做到了。 numberOfSheets 如您所料,w 似乎保持为零,而 i 正常工作。
-
您是否单步执行此代码以验证所有值均按预期设置?