public class SNMPTrapView { public long Id { get; set; } [Display(Name = "ID")] public string TrapId { get; set; } [Display(Name = "時間")] public string TrappedOn { get; set; } [Display(Name = "類型")] public string Type { get; set; } public string Status { get; set; } [Display(Name = "內容")] public string Content { get; set; } [Display(Name = "說明")] public string Desc { get; set; } [Display(Name = "結案")] public string Done { get; set; } }案例: 想要匯出到excel,但是只想要顯示有DisplayAttribute的欄位
參考了這兩篇文章
https://stackoverflow.com/questions/7027613/how-to-retrieve-data-annotations-from-code-programmatically
https://stackoverflow.com/questions/6637679/reflection-get-attribute-name-and-value-on-property
改寫成
public static List<Tuple<string, string>> GetPropNameAndAttrName<T>() { var result = new List<Tuple<string, string>>(); PropertyInfo[] props = typeof(T).GetProperties(); foreach (PropertyInfo prop in props) { object[] attrs = prop.GetCustomAttributes(true); if (attrs.Any()) { var attr = (DisplayAttribute)attrs[0]; if (!string.IsNullOrEmpty(attr.Name)) { result.Add(new Tuple<string, string>(prop.Name, attr.Name)); } } } return result; }
透過 .Net Core API 網站顯示
[HttpGet("obj")] public IActionResult GetObject() { return new ObjectResult(CommonTool.GetPropNameAndAttrName<SNMPTrapView>()); }
瀏覽器顯示結果
確定如預期,完成剩下的程式,產出excel報表
// GET: api/snmptrap/excel [HttpGet("excel")] public async Task<IActionResult> GenerateExcelAsync(SNMPTrapSearching model) { var report = await Task.Factory.StartNew(() => _snmpTrapService.Get(model)); var memoryStream = new MemoryStream(); using (var document = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook)) { var sheetData = CommonTool.CreateSheetData(document, "SNMPTrap"); var props = CommonTool.GetPropNameAndAttrName<SNMPTrapView>(); var row = new Row(); foreach (var prop in props) // header { row.Append(new Cell() { CellValue = new CellValue(prop.Item2), DataType = CellValues.String }); } sheetData.AppendChild(row); foreach (var item in report) // body { row = new Row(); foreach (var prop in props) { var value = (string)item.GetType().GetProperty(prop.Item1).GetValue(item, null); row.Append(new Cell() { CellValue = new CellValue(value), DataType = CellValues.String }); } sheetData.AppendChild(row); } } memoryStream.Seek(0, SeekOrigin.Begin); var fileName = $"SNMPTrap_Report_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx"; return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); }