I have a set of Excel data which I read and assign to corresponding columns of an Excel table. In our Excel we have provided the user the option to rearrange the Excel column fields at runtime.
int rowIndex =int.Parse(ExcelSettingManager.ItemLine);
int lastItem = numberOfFilledRows();
numberOfFilledRows();
int maxIndex = rowIndex + lastItem;
MSExcel.Range cell = null;
while (rowIndex < maxIndex)
{
DataRow dataRow = ExcelDataManager.Instance.DocumentItemTable.NewRow();
cell = this.worksheet.Range[ExcelSettingManager.LineItemNo + rowIndex.ToString()];
if (cell.Value2 == null)
{
return;
}
dataRow["LineItemNo"] = cell.Value;
ExcelUtilities.ReleaseResources(cell);
if (ExcelSettingManager.CostCenter != string.Empty)
{
cell = this.worksheet.Range[ExcelSettingManager.CostCenter + rowIndex.ToString()];
dataRow["CostCenter"] = cell.Value;
ExcelUtilities.ReleaseResources(cell);
}
if (ExcelSettingManager.GLAccount != string.Empty)
{
cell = this.worksheet.Range[ExcelSettingManager.GLAccount + rowIndex.ToString()];
dataRow["GeneralLedgerAccount"] = cell.Value;
ExcelUtilities.ReleaseResources(cell);
}
if (ExcelSettingManager.Description != string.Empty)
{
cell = this.worksheet.Range[ExcelSettingManager.Description + rowIndex.ToString()];
dataRow["ItemText"] = cell.Value;
ExcelUtilities.ReleaseResources(cell);
}
}
internal int numberOfFilledRows()
{
int noft = 0;
string sNextCell = ExcelSettingManager.LineItemNo ExcelSettingManager.ItemLine;
MSExcel.Range cell = this.worksheet.Range[sNextCell];
while(!string.IsNullOrEmpty(cell.Value))
{
ExcelUtilities.ReleaseResources(cell);
noft++;
sNextCell = ExcelSettingManager.LineItemNo + (int.Parse(ExcelSettingManager.ItemLine) + noft).ToString();
cell = this.worksheet.Range[sNextCell];
}
return noft;
}
If my Excel has 10 rows according to the current logic, it will read cell by cell each row and will assign to the corresponding Excel table column.
This is having a lot of performance impact. When there are more rows, the performance is worse.
How can I increase performance of this code?
.NewRow()
, the.ReleaseResources()
, the string concatenation, the use of.Range()
instead of specifying the cell row and column by using integers? Even if you don't want to use a profiler (you should), there are ways of determining if certain lines are a speed hit. \$\endgroup\$