I am using the NPOI library within a c# console application to write some information to excel. The problem i seem to be facing is that the code will not run from within a a for loop (if i take the same code out of the for loop, it works and updates the spreadsheet).
I have stepped through the code, so i know it hits the createRow, SetCellValue etc in the loop, so i know its not an issue with the loop, just doesnt seem to want to do it in the loop. funny thing is i have almost identical code (VB.Net not C#) which works?
Sample C# Code
using (var fs = new FileStream(templateName, FileMode.Open, FileAccess.Read))
{
var template = new HSSFWorkbook(fs, true);
var sheet = template.GetSheet(sheetName);
int rowCount = 1;
int colCount = 0;
colCount = 0;
NPOI.SS.UserModel.Row rowIn = null;
NPOI.SS.UserModel.Cell cellIn = null;
//foreach (var item in items)
for(int i = 0; i < items.Count; i++)
{
rowIn = sheet.CreateRow(i);
cellIn = rowIn.CreateCell(1);
cellIn.SetCellValue("A");
}
//....rest of the code to save the file
}
The following VB.Net code works, it is different from the c# code where i have tried to change it to see if it would work, but previously the two was just a standard port.
Using fs As New FileStream(Server.MapPath("/exporttemplates/tender-export-template.xls"), FileMode.Open, FileAccess.Read)
Dim templateWorkbook As New HSSFWorkbook(fs, True)
Dim sheet As HSSFSheet = templateWorkbook.GetSheet("Products")
Dim productsBids As List(Of TenderProductBid) = TenderProductBid.GetTenderProductBids(tbid.id)
Dim i As Integer = 1
For Each pb As TenderProductBid In productsBids
Dim rowIn As NPOI.SS.UserModel.Row = sheet.CreateRow(i)
rowIn.CreateCell(0).SetCellValue(pb.product.productName)
rowIn.CreateCell(1).SetCellValue(pb.quantity)
rowIn.CreateCell(2).SetCellValue(pb.bid)
i += 1
Next
'....rest of the code to save the file
End Using
The documentation is not clear so it is not plain to see what exactly is wrong with the code for it work outside of a loop but no in it, when the loop is working and the information is being passed?