I'm trying to write an Extension methods that adds a generic Item T to the workbook, I've got problem since the UsedRange.RowCount is not incremented after InsertMethod is called
public static RowItem<T> AddItem<T>(this SpreadsheetGear.IWorksheet worksheet, T item) where T : class
{
int currentRow = worksheet.UsedRange.RowCount;
//int currentRow = worksheet.UsedRange.RowCount;
RowItem<T> newItem = new RowItem<T>
{
Item = item,
RowIndex = currentRow
};
var reflected = item.GetType().GetProperties();
for (int i = 0; i < reflected.Length; i++)
{
object value = reflected[i].GetValue(item);
worksheet.Cells[currentRow, i].Value = value;
}
worksheet.UsedRange.Insert(SpreadsheetGear.InsertShiftDirection.Down);
worksheet.WorkbookSet.CalculateFull();
return newItem;
}
public static IEnumerable<RowItem<T>> AddItems<T>(this SpreadsheetGear.IWorksheet worksheet, IEnumerable<T> items) where T : class
{
var lst = new List<RowItem<T>>();
foreach (var item in items)
{
var newItem = AddItem<T>(worksheet, item);
lst.Add(newItem);
}
return lst;
}
It's always 1 ...what am I doing wrong? my dummy class is
public class Dummy
{
public string Desciption { get; set; }
public double Value { get; set; }
public DateTime Data { get; set; }
}
And I add items as
using (var _ = new WorkbookViewLock(workbookView1))
{
var worksheet = workbookView1.ActiveSheet.Workbook.Worksheets[0];
worksheet.AddItem<Dummy>(dummy);
worksheet.AddItem<Dummy>(dummy2);
}
If you are starting out with a blank worksheet (are you?), then it would make sense that the first two checks you make to
worksheet.UsedRange.RowCountin your code would have a value of 1.This is because the
UsedRangeof a blank worksheet will always be A1, which would correspond to aUsedRange.RowCountvalue of 1. That accounts for a value of 1 for your firstAddItem(...)call.The second
AddItem(...)call is now looking at a worksheet that is populated with data, but still only 1 row since you've only added a singleDummyobject at this point.If you were to add a third
Dummyobject, you would see that theUsedRangeincrements to a value of 2.FYI: You might have an additional issue with with your
worksheet.UsedRange.Insert(...)line, since this will insert the number of rows thatUsedRangecurrently consists of. It seems to me that if you are adding just a singleDummyobject with this extension method, you should only insert, at most, one row...and that depends on where you want each newDummyrow to get added to the worksheet--the top or bottom of the used range. If you are inserting the newDummyobject at the top of theUsedRange, you should only applyInsert(...)on the top row of theUsedRange. If you are inserting the newDummyobject at the bottom of the UsedRange, noInsert(...)call is necessary at all since there's nothing below the UsedRange to shift down.