Scenario is to generate an excel report that has ~ 150 data columns. Now I need to manage the column properties like Width, BackgroundColor, Font etc.
The approach that I am using relies on reflection. I have a class that has ~ 150 constants for column header text. Another custom attribute class to store column properties. These attributes are applied to the constants.
During column creation using reflection I am accessing all the constants to create the header text(Constant ordering in class defines column ordering) and the attribute for column properties.
private void CreateHeader(Excel.Worksheet xl_WorkSheet, FieldInfo[] fi_Header)
{
ColumnProperties c;
System.Attribute[] customAttributes;
for (int i = 0; i < fi_Header.GetLength(0); i++)
{
xl_WorkSheet.get_Range(xl_WorkSheet.Cells[1, i+1], xl_WorkSheet.Cells[2, i+1]).Merge(false);
//Set the header text.
xl_WorkSheet.get_Range(xl_WorkSheet.Cells[1, i + 1], xl_WorkSheet.Cells[2, i + 1]).FormulaR1C1 =
fi_Header[i].GetValue(null).ToString();
//Set cell border.
xl_WorkSheet.get_Range(xl_WorkSheet.Cells[1, i + 1],
xl_WorkSheet.Cells[2, i + 1]).BorderAround(Excel.XlLineStyle.xlContinuous,
Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
//Get custom attribute ~ Column attribute.
customAttributes = (System.Attribute[])fi_Header[i].GetCustomAttributes(typeof(ColumnProperties), false);
if (customAttributes.Length > 0)
{
c = (ColumnProperties)customAttributes[0];
//Set column properties.
xl_WorkSheet.get_Range(xl_WorkSheet.Cells[1, i + 1],
xl_WorkSheet.Cells[2, i + 1]).Interior.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromName(c.Color));
xl_WorkSheet.get_Range(xl_WorkSheet.Cells[1, i + 1],
xl_WorkSheet.Cells[2, i + 1]).ColumnWidth = c.Width;
}
}
}
EDIT: Code to get constants
private FieldInfo[] GetHeaderConstants(System.Type type)
{
ArrayList constants = new ArrayList();
FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
foreach (FieldInfo fi in fieldInfos)
{
if (fi.IsLiteral && !fi.IsInitOnly)
constants.Add(fi);
}
return (FieldInfo[])constants.ToArray(typeof(FieldInfo));
}
Main objective is to make the excel file generation generic/less maintainable. Is the approach fine or there are any other better alternatives.
EDIT 2: Constants class
public class ExcelHeaders
{
[ColumnProperties(Width=10, Color="LemonChiffon")]
public const string S_NO = "S.No";
[ColumnProperties(Width = 20, Color = "WhiteSmoke")]
public const string COLUMN_HEADER = "Header Text";
}