简体   繁体   中英

Copy row with formulas and format then insert a new row in excel C#

I am writing a C# application where I have an excel default template file where the first 10 rows are kind of fixed. Then the following row11 have some cells which are formulas and formats, and it's same for the row 12 and 13 where they have the same formulas and format except that they are automated filled using row 11 so for example if row11 col10 has a formula using row11 col9 cell then for row12 col10 will have the same formula except that it will be using row12 col9 and so on. So I wonder how I can add a row after row 13 where it will have the same formulas and format as the ones above and shifts the rest of rows downwards in the rest of the excel worksheet downwards. Below is how I opened the excel file:

Excel.Application myApp = new Excel.Application();
Excel.Workbook my_workbook = myApp.Workbooks.Open(@"C:\my Work\my_template.xlsx");
Excel.Worksheet my_ws = my_workbook.Worksheets[1];

Here is alink to the template file where I highlighted in red the two rows which I want to copy then insert downward, so what I would want to do is copy row 22 with it's format and formulas then insert it to be row 23 then copy row 37 with it's format and formulas then insert it to be row 38. Could you advise?

This is just pseudo code, but maybe it will get you started, the formulas should automatically adjust based on the new row:

//insert new row at 23 (only do this if you want to shift product table down)
   my_ws.InsertRow(23);


    //Source Range
    Range sourceRange = my_ws.Cells.CreateRange(“A22:Z22”);
    
    //Destination range
    Range destRange = my_ws.Cells.CreateRange(“A23:Z23”);
    
    destRange.Copy(sourceRange);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM