Copy Format from One Range to Another in Excel using C#

This example demonstrates how to copy format from one excel range to another excel range. For this, you need to use PasteSpecial() method of Range with xlPasteFormats.

For example, you have set the desired format in range “B1:B5” of sheet1 of “Test Excel.xlsx” and you need to copy the same format to the range “C1:C5” of sheet1 of the same workbook as shown in below figure.

C# excel format painting example

You need to refer to our previous article working with Excel using C# to open, accessing the required sheet, saving and closing the excel and use the below given steps to write the code snippet for copying format from the specified range to the specified range.

// declares the source range object
Microsoft.Office.Interop.Excel.Range sourceRange = excelSheet.get_Range("B1:B5");

// declares the destination range object
Microsoft.Office.Interop.Excel.Range DestRange = excelSheet.get_Range("C1:C5");

// copy the source range
// paste format to destination range
DestRange.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteFormats, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);

After executing the above code, you can see that format from range “B1:B5” has been copied to range “C1:C5” as shown in below figure.

excel format painting in C#

You can specify range in the C# sample code as per your requirement and can get excel format painting automatically.

Leave a Reply