在导出的Excel数据中使用列标题的“显示名称”属性

时间:2014-12-16 17:44:16

标签: c# .net excel attributes epplus

我正在尝试使用DisplayName属性来修改导出到Excel文件的数据中的列标题。我想要"我的名字"但得到" MyName"。数据是从查询返回的数据,转换为List,然后转换为DataTable,然后导出到Excel。 我还能尝试什么?

some discussion here表示正在添加此功能。

使用.NET Framework 4

    public class MyExcelViewModel
    {
            private string myName;
            //[System.ComponentModel.DisplayName("Mine Name")] // no effect
            //[System.ComponentModel.DataAnnotations("My Name")] // doesn't compile
            //[System.ComponentModel.DisplayNameAttribute("My Name")] // no effect
            [Display(Name = "My Name")] // no effect
            public string MyName { get; set; }
    }

    public class MyController : Controller
        // initialize exportList
        IList<MyExcelViewModel> exportList = new List<MyExcelViewModel>(fromQueryList.Count);
        foreach (var value in fromQueryList)
        {
            exportList.Add(new MyExcelViewModel());
        }

        DataTable dataTable = ConvertListToDataTable(exportList); // convert to DataTable
        Export_EPPlus(dataTable); // export

        private void Export_EPPlus(DataTable dataTable)
        {
                 using (ExcelPackage package = new ExcelPackage())
                 {
                     ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(" Results");

                     // Load the datatable into the sheet, starting from cell A1.
                     worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);

                     worksheet.View.FreezePanes(2, 1); // freeze first row & column
                     worksheet.Row(1).Style.Font.Bold = true;

                     worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); // autofit column width

                     for (int rowNumber = worksheet.Dimension.Start.Row; rowNumber <= worksheet.Dimension.End.Row; rowNumber++)
                     {
                         int rowIndex = rowNumber % 2; // even => 0, odd => 1
                         ExcelRow excelRow = worksheet.Row(rowNumber);
                         ExcelFill excelFillRow = excelRow.Style.Fill;
                         excelFillRow.PatternType = ExcelFillStyle.Solid;
                         switch (rowIndex)
                         {
                             case 0:
                                 excelFillRow.BackgroundColor.SetColor(System.Drawing.Color.White);
                                 break;
                             case 1:
                                 excelFillRow.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                                 break;
                         }
                     }

                     try
                     {
                         // Write to client
                         Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                         Response.AddHeader("content-disposition", "attachment;  filename="Results-EPPlus.xlsx");
                         Response.BinaryWrite(package.GetAsByteArray());

                     }
                     catch (Exception ex)
                     {
                         System.Diagnostics.Trace.WriteLine("MyController.Export_EPPlus(): exception: " + ex);
                     }
                 }
             }

        public static DataTable ConvertListToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }
}

1 个答案:

答案 0 :(得分:1)

DisplayName属性只适用于4.0,不幸的是3.1。在3.1版中执行此操作的唯一方法是手动设置Caption记录中每个DataColumn的{​​{1}},如here所示。

我写了一篇博文,其中包含了实践中的其他新4.0功能here

作为证明,以下是EPPlus 3.1中的相关代码,它以DataTable方法打印列标题:

LoadFromDataTable