3

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.

1

2 Answers 2

4

You could retrieve it from the model metadata:

ws.Cell(2.1).Value = ModelMetadata.FromLambdaExpression<DCArrival, string>(x => x.LocationType, new ViewDataDictionary<DCArrival>(firstRow)).DisplayName;

or write an extension method:

public static class ModelMetadataExtensions
{
    public static string GetName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> ex)
    {
        return ModelMetadata
            .FromLambdaExpression<TModel, TProperty>(ex, new ViewDataDictionary<TModel>(model))
            .DisplayName;
    }
}

and then:

ws.Cell(2.1).Value = firstRow.GetName(x => x.LocationType);
ws.Cell(2.2).Value = firstRow.GetName(x => x.CurrencyISOCode);

UPDATE:

As per a new requirement that was expressed in the comments section in order to loop through all properties and read the display attribute you could use the following:

var properties = typeof(DCArrival).GetProperties(); 
foreach (var property in properties) 
{
    var displayAttribute = property
        .GetCustomAttributes(typeof(DisplayAttribute), true)
        .FirstOrDefault() as DisplayAttribute;
    string displayName = property.Name;
    if (displayAttribute != null)
    {
        displayName = displayAttribute.Name;
    }

    // TODO: do something with the display name for this property
} 
6
  • I di not understand the (firstvalue) but: ws.Cell(2,1).Value = ModelMetadata.FromLambdaExpression<DCArrival, string>(x => x.LocationType, new ViewDataDictionary<DCArrival>()).DisplayName; worked fine. Thank you Feb 15, 2012 at 15:08
  • @PatrikLindström, that was a typo. It must be firstRow. I have fixed it. Feb 15, 2012 at 15:12
  • What if I would elaborate and wanted to loop over all the members of my DCArrival. I tryed this but then the DisplayName is always null. Type type = typeof(DCArrival); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { string displayName = ModelMetadata.FromLambdaExpression<DCArrival, string>(x => property.Name, new ViewDataDictionary<DCArrival> (firstRow)).DisplayName; ws.Cell(startRow, j++).Value = displayName; } Feb 15, 2012 at 18:21
  • @PatrikLindström, oh no, this cannot work as you imagine. Please see my updated answer. Feb 15, 2012 at 18:24
  • I tryed the extension method as well. Ill stick to that one. Its more beautiful. Feb 15, 2012 at 18:36
1

You guys are doing it wrong...

static void Main()
{

    var wb = new XLWorkbook();
    var ws = wb.Worksheets.Add("People");

    var people = new List<Person>
    {
        new Person{Name = "John Doe", DOB = new DateTime(1980,1,1)},
        new Person{Name = "Jane Doe", DOB = new DateTime(1985,1,1)}
    };

    ws.FirstCell().InsertTable(people);

    ws.Columns().AdjustToContents();
    wb.SaveAs(@"C:\MyFiles\Excel Files\Sandbox.xlsx");
}

class Person
{
    [Display(Name = "Person's Name")]
    public String Name { get; set; }

    [Display(Name = "Date of Birth")]
    public DateTime DOB { get; set; }
}

enter image description here

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.