Problems writing Excel

I want to write to a sheet on Excel from data from C#. It is OK, but I don't know about how to change cells text design (ex. font, color ...) and how to align the letters left or right? I searched webpages and books, but nothing organized information founded. To put it shortly, I want to know the methods which can change font color and align right left... so on.


Please find here some snippets you're looking for. The snippets are using the Microsoft Office foundation libraries (Microsoft.Office.Interop), no EPPlus, no Componentsource or else.

Having something like this as preparation:

MSExcel.Application excelApp;
excelApp = new Microsoft.Office.Interop.Excel.Application();
Workbook workBook;
Worksheet sheet;
Excel.Range range;
workBook = excelApp.Workbooks.Open(...);
sheet = (Worksheet)workBook.ActiveSheet;
range = (Excel.Range)sheet.get_Range("A5:C7", Type.Missing); // Example of getting a range object

Then you can use objects like this:

1) Setting a border edge bottom to a range:

range.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlHairline;

2) Setting a background color to a range:

range.interior.Pattern = Excel.XlPattern.xlPatternSolid;
range.interior.PatternColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.interior.ThemeColor = Excel.XlThemeColor.xlThemeColorDark1;
range.interior.TintAndShade = -0.249977111117893; // This was captured by macro recording
range.interior.PatternTintAndShade = 0;

3) Setting a column width:

range.ColumnWidth = width;

4) Setting horizontal alignment to center:

range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

I recommend you take these snippets and google around with, because you'll find much more :-)

Also a good procedure is to record some activities as macro in Excel VBA. Then, again with some googleing, you should be able to translate the terms you see to C#. Good luck!

Need Your Help

Is there a way to completely block the ability to take screenshots in Android?

android screenshot screen-capture

I'm currently developing a light-weight application where in one part of the app I would like to COMPLETELY take away the ability to take a screenshot in Android. When I say screenshot, I'm talking...

PHP Mail form doesn't work when certain text is entered

php html email post

I'm working on a PHP mail form and for some reason only certain text doesn't send through. It has me baffled and I can't even think of how to Google an answer.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.