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!