I have a viewmodel where the properties have display names. I am now making an Excel sheet with the same data in as the grid in the webpage. I am using closed xml (which uses openxml) to create the Excelsheet on the server and send it to the webclient when they want to download data as Excel. When I write the header row in Excel openxml stream I want to reuse the displayname that I already have defined. But I can't figure out what to call on.
Here is an example of the display name. ( For the example I only use two, reality there are many many more columns) :
using System.ComponentModel.DataAnnotations;
public class DCArrival : IDCArrival
{
[Display(Name = "Via Transit")]
public String LocationType { get; set; }
[Display(Name = "Currency")]
String CurrencyISOCode { get; }
}
Then I want to use this displayname when I create the header row. Mark the pseudocode that tries to explain what I want to get hold of:
private MemoryStream CreateExcelFile(ICollection<DCArrival> dcArrToShow
, QueryStrInput queryStrInput)
{
try
{
// Create an Excel Workbook
XLWorkbook wb = new XLWorkbook();
// Add the worksheet with data
IXLWorksheet ws = wb.Worksheets.Add("New Worksheet");
// Add my data that was displayed in the html table ...
ws.Cell(1, 1).SetValue("Hello World");
//Add Header row. By taking a object in the collection and figure out its
// display name
DCArrival firstRow = dcArrToShow.First();
// Here comes my problem. Here is my dream up mockup code
ws.Cell(2,1).Value = firstRow.LocationType.DisplayAttribute.GetName()
ws.Cell(2,2).Value = firstRow.CurrencyISOCode.DisplayAttribute.GetName()
// back to reality
//this is how easy I can get all data from Collection
ws.Cell(3, 1).Value = dcArrToShow.AsEnumerable();
// All done
MemoryStream ms = new MemoryStream();
wb.SaveAs(ms);
return ms;
}
catch (Exception e)
{
string errmsg = String.Format("Failed to create Excel file: {0}",
e.Message);
throw new Exception(errmsg, e);
}
I have looked at the http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx But I do not understand how I get a hold of it. I understand that this is magically fixed for you when you are using normal mvc 3 html rendering. When I Google these concepts I get drowned in blogs who wants to explain basic validation in MVC 3.