We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

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 08:50 AM

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.
Live Chat Icon For mobile
Up arrow icon