2
votes

My sample code to change the cell color is this. range refers to a cell range.

range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);

If i try to change the cell color back to white. Im using this.

range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);

But this erases my cell range grid lines(default color of the lines are grey) and everything becomes white. i.e.only 'range' grid lines becomes white and all other cells have the default excel grid color. Thanks

2
Welcome to Stack Overflow! It is a horrible idea to use Office Interop from ASP.NET or another server technology. These APIs were written for use in a desktop application, for automating Office (a suite of desktop applications). Server applications are different in many ways that make it a very, very bad idea to use Office Interop in them. It's also unsupported by Microsoft, and may violate your Office license. See Considerations for server-side Automation of OfficeJohn Saunders
@JohnSaunders Thank you :). As i wanted to access excel through source code I used ASP.net. Just educational purpose. Thank you for the informationNathi
Ok, you should use a desktop application to work with Office Automation (console, Windows Forms, or WPF).John Saunders

2 Answers

3
votes

System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);The problem is occuring because the interior colour of the range of cells is not actually white (it just appears white). Each cell by default is actually transparent (-4142).

So do this when you want to set it back to "normal":

range.Interior.Color = -4142

Edit: Best to use Constants and -4142 is equal to xlNone.

Anonymous Type I don't understand why this doesn't work for you? Can you please refine your question? I tried the following and it worked just fine..

const Int32 transparent_Color = -4142;
//Set Yellow
var Rng = ActiveSheet.Range["D5:E7"];
Rng.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);

//Set transparent (gridlines come back, so long as you haven't got other code that is interacting with your cells)
var Rng = ActiveSheet.Range["D5:E7"];
Rng.Interior.Color = transparent_Color;
1
votes

Trick: Open Excel > Developer Toolbar > Record Macro > select/highlight range > change backcolor to yellow > change backcolor to white. Now set the Style to Normal.

Stop the Macro from recording.

Then press Alt + F11 to go into VBA Editor and look at the code in Module 1.

Simply convert that code to C# - it is almost the exact same Object Model in C# as it is with VB.