Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do alternate row shading using Office.Interop.Excel?

I'm using Office Interop via C# 4.0 to write an Excel file. I would like to shade alternating rows. I know how to do this with the GUI in Excel. I could also loop through each row to provide the shading, but this option is unacceptably slow with large data sets. Is there a way, using Office.Interop.Excel to set the conditional formatting options found in the Excel GUI?

EDIT: Added more information

Using C# with .NET 4.0 and Office Interop 2007

like image 212
nathan Avatar asked Apr 05 '11 14:04

nathan


1 Answers

After some research and playing around I believe I have found the best answer. The following code will alternate row colors for the worksheet.

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Interop.Excel.Application();
Workbook workbook = excel.Workbook.Add();
Worksheet worksheet = workbook.Worksheets.Item[1];

FormatCondition format = worksheet.Rows.FormatConditions.Add(XlFormatConditionType.xlExpression, XLFormatConditionOperator.xlEqual, "=MOD(ROW(),2) = 0");
format.Interior.Color = XlRgbColor.rgbBlue;
like image 124
nathan Avatar answered Sep 28 '22 15:09

nathan