Copy row in Excel

I'm trying to copy a row and paste it right below it.

I got it to insert a new row, but it's not copying the formatting & values

Here is the code I am using:

            string filePath = @"Checklist.xlsx";

            string fileOutPath = @"Checklist 2.xlsx";


            using (ExcelEngine excelEngine = new Syncfusion.XlsIO.ExcelEngine())

            {

                IApplication application = excelEngine.Excel;

                application.DefaultVersion = ExcelVersion.Xlsx;


                IWorkbook sourceWorkbook = application.Workbooks.Open(filePath, ExcelOpenType.Automatic);

                IWorksheet sourceWorksheet = sourceWorkbook.Worksheets[0];


                sourceWorksheet.InsertRow(10);

                IRange source = sourceWorksheet.Rows[9];

                IRange destination = sourceWorksheet.Rows[10];

                source.CopyTo(destination, ExcelCopyRangeOptions.All);


                sourceWorkbook.Version = ExcelVersion.Xlsx;

                sourceWorkbook.SaveAs(fileOutPath);

            }



1 Reply

KK Konduru Keerthi Konduru Ravichandra Raju Syncfusion Team November 23, 2022 01:50 PM UTC

Hi Michael,


We suggest you to use ExcelInsertOptions while inserting the row, to achieve your requirement. Please find the code snippet below.


using (ExcelEngine excelEngine = new Syncfusion.XlsIO.ExcelEngine())

{

    IApplication application = excelEngine.Excel;

    application.DefaultVersion = ExcelVersion.Xlsx;

 

    IWorkbook sourceWorkbook = application.Workbooks.Open("../../Data/Sample.xlsx", ExcelOpenType.Automatic);

    IWorksheet sourceWorksheet = sourceWorkbook.Worksheets[0];

 

    sourceWorksheet.InsertRow(10, 1, ExcelInsertOptions.FormatAsBefore);

    IRange source = sourceWorksheet.Rows[8];

    IRange destination = sourceWorksheet.Rows[10];

    source.CopyTo(destination, ExcelCopyRangeOptions.All);

 

    sourceWorkbook.Version = ExcelVersion.Xlsx;

    sourceWorkbook.SaveAs("Output.xlsx");

    System.Diagnostics.Process.Start("Output.xlsx");

}


Regards,

Keerthi.


Loader.
Up arrow icon