Home » excel » Is there a way to mimic format painter in Excel using C#?

Is there a way to mimic format painter in Excel using C#?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am writing a C# program to manipulate a couple of Excel files (xls format) using Microsoft.Office.Interop.Excel. What I need to do is to add a new sheet and write some data, whose format is similar as the data in some existing sheets. So basically I would like to find a way to perform the action like format painter when we modify Excel file manually. What I mean is, I need to set the number format, the background color, font, font color, alignment, and so on.

I tried to achieve this by setting both NumberFormat and Style properties in the Cells that I need to modify. The code looks like this:

newSheet.Cells[6, 3].Value2 = 10;
newSheet.Cells[6, 3].NumberFormat = existingSheet.Cells[5, 4].NumberFormat;
newSheet.Cells[6, 3].Style = existingSheet.Cells[5, 4].Style;

From what I can see, the NumberFormat is OK now (I have set correctly the date, percent, and other number formats by doing this). But the background color, font, font color stuff do not get changed as desired. So how should I do? Thank you!

How to&Answers:

Try to use Copy and PasteSpecial methods.

  1. Copy all the content of the source cell. Source cell has the expected formats. In your code it is the cell Cells[5 ,4]

  2. PasteSpecial only the formats to the target cell. In your code it is the cell Cells[6, 3]

Example:

Microsoft.Office.Interop.Excel.Range source = existingSheet.Cells[5, 4];
source.Copy(); // Copy everything from the source cell to the clipboard

Microsoft.Office.Interop.Excel.Range target = newSheet.Cells[6, 3];
target.Value = 456; // Write value to the target cell and ...
target.PasteSpecial(XlPasteType.xlPasteFormats); // Paste only formats from the source cell