@rahulsingh27
The moved formula was caused by the option “InsertRows” with the default value “True”. When inserting rows, the existing row is sure to be moved downward so the formula be moved too. This behavior is as designed and we should not change it. As Amjad’s sample code shows, you may set this option to false, so the formula will be kept in the original position.
However, if you need the formula to be applied to all inserted rows for the importing, the design of the template or your code should be changed a bit. You may create one table for the destination range manually in ms excel, or by code like:
...
row2["TotalSales"] = 110;
dt.Rows.Add(row2);
//create table for the destination
ws.RemoveAutoFilter();
ws.ListObjects.Add("A1", "H2", true);
ListObject lo = ws.ListObjects[0];
lo.ListColumns[lo.ListColumns.Count - 1].Formula = ws.Cells[1, 7].Formula;
Console.WriteLine(ws.Cells[1, 7].Formula);
ws.Cells.ImportData(dt, 1, 0, new ImportTableOptions { IsFieldNameShown = false, ShiftFirstRowDown = false });
...
For formula of table’s column, it will be copied for all rows that be imported.
Another solution is that you apply the formula for all imported rows by extra code:
...
row2["TotalSales"] = 110;
dt.Rows.Add(row2);
Console.WriteLine(ws.Cells[1, 7].Formula);
string fml = ws.Cells[1, 7].Formula; //record the original formula
ws.Cells.ImportData(dt, 1, 0, new ImportTableOptions { IsFieldNameShown = false, ShiftFirstRowDown = false });
ws.Cells[1, 7].SetSharedFormula(fml, dt.Rows.Count, 1); //apply formula to all imported rows
...