繁体   English   中英

读取自定义属性的值

[英]Read value of custom attributes

我只想导出 Export = true 的属性。

我有另一种方法可以接受任何 object(不仅仅是 PlanSetup),打开它,并将行添加到 ExcelWorkBook。 我设法获得了 object 的类型,但获得自定义属性的值是我苦苦挣扎的地方。 我可以将行/列添加到 excel 但想在添加之前检查 Export = true。

保留注释代码,以便您可以看到我尝试过的内容。

public class PlanSetup
    {
        public int PlanSetupLogID { get; set; }
        [Custom(Export = true)]
        public string PlanNumber { get; set; }
        [Custom(Export = true)]
        public string OrganizationID { get; set; }
        [Custom(Export = true)]
        public string AssociateID { get; set; }
        public string ChangedFieldsList { get; set; }
        public string GET_ResponseJSON { get; set; }
        public string JSONRequest { get; set; }
        public string JSONResponse { get; set; }
        [Custom(Export = true)]
        public string Status { get; set; }
        [Custom(Export = true)]
        public string CreatedDate { get; set; }
}

   public async Task<byte[]> ExportDataToExcel(IEnumerable<object> data, string reportName = null)
    {
        byte[] excelData = null;
        try
        {
            if (data != null)
            {
                Type type_info = data.FirstOrDefault().GetType();
                System.Reflection.PropertyInfo[] properties_info = type_info.GetProperties();
                //System.Reflection.MemberInfo info = 
                System.Reflection.MemberInfo[] myMembers = type_info.GetMembers();
                List<string> ExportColumns = new List<string>();

                properties_info = properties_info.Where(item => item.CustomAttributes.Count() > 0).ToArray();
                foreach (System.Reflection.PropertyInfo p in properties_info)
                {
                    //if (p.CustomAttributes.Where(item => item.NamedArguments.Where(lol => lol.MemberInfo.Name);
                    //var ps = p.CustomAttributes.Where(item => item.NamedArguments.Where(sp => sp.MemberName == "Export");
                    //List<System.Reflection.CustomAttributeNamedArgument> cad = (System.Reflection.CustomAttributeNamedArgument)p.CustomAttributes.Select(item => item.NamedArguments).ToList();
                }


                //System.Reflection.MemberInfo info = typeof(type_info);


                foreach (System.Reflection.MemberInfo m in myMembers)
                {

                    if (m.CustomAttributes.Count() > 0)
                    {
                        if (m.Name == "Export")
                        {
                            ExportColumns.Add(m.Name);
                        }
                    }
                    foreach (object attrib in m.GetCustomAttributes(true))
                    {
                        Console.WriteLine(attrib);
                    }
                }

                //Object[] lolll = myMembers.Where(item => item.GetCustomAttributes(true));
                //for (int i = 0; i < myMembers.Length; i++)
                //{
                //    Object[] myAttributes = myMembers[i].GetCustomAttributes(true);
                //    if (myAttributes.Length > 0)
                //    {
                //        Console.WriteLine("\nThe attributes for the member {0} are: \n", myMembers[i]);
                //        for (int j = 0; j < myAttributes.Length; j++)
                //            Console.WriteLine("The type of the attribute is {0}.", myAttributes[j]);
                //    }
                //}

                using (var package = new ExcelPackage())
                {
                    //int x = 1, y = 1;
                    var worksheet = package.Workbook.Worksheets.Add(reportName);

                    int totalRows = data.Count();
                    int firstRow = 1;
                    int secondRow = 2;
                    int i = 1;
                    foreach (System.Reflection.PropertyInfo prop in properties_info)//Adding Headers
                    {

                        worksheet.Cells[firstRow, i].Value = prop.Name;

                        //if (prop.CustomAttributes.Select(item => item.NamedArguments[0].MemberName == "Export").FirstOrDefault())
                        //{
                        //    worksheet.Cells[firstRow, i].Value = prop.Name;
                        //}

                        //var lol = prop.CustomAttributes.Select(item => item.NamedArguments[0].MemberName == "Export");

                        //if(prop?.CustomAttributes?.Select(item=> item.NamedArguments.Select(i1=> i1.MemberName='Export')
                        i++;
                    }
                    foreach (var p in data)//Adding actual data rows.
                    {
                        int j = 1;
                        foreach (System.Reflection.PropertyInfo prop in properties_info)
                        {
                            worksheet.Cells[secondRow, j].Value = prop.GetValue(p, null);
                            j++;
                            //if (prop.CustomAttributes.Select(item => item.NamedArguments[0].MemberName == "Export").FirstOrDefault())
                            //{
                            //    worksheet.Cells[secondRow, j].Value = prop.GetValue(p, null);
                            //    j++;
                            //}
                        }
                        secondRow++;
                    }
                    string firstRowAllColumnsAddress = "A1:Y1";//worksheet.Cells[1, 1, 1, 24]
                    worksheet.Cells[firstRowAllColumnsAddress].Style.Font.Bold = true;
                    worksheet.Cells.AutoFitColumns();
                    await Task.Run(() => { excelData = package.GetAsByteArray(); });
                }
            }
        }
        catch (Exception e)
        {
            throw (e);
        }
        return excelData;
    }





 /***FIXED - Here is the working solution***/

     public async Task<byte[]> ExportDataToExcel(IEnumerable<object> data, bool exportDecorator, string reportName = null)
            {
                byte[] excelData = null;
                try
                {
                    if (data != null)
                    {
                        Type type_info = data.FirstOrDefault().GetType();

                        System.Reflection.PropertyInfo[] properties_info = exportDecorator ? type_info.GetProperties().Where(p => p.GetCustomAttribute<CustomAttribute>()?.Export == true).ToArray() : type_info.GetProperties();

                        using (var package = new ExcelPackage())
                        {
                            //int x = 1, y = 1;
                            var worksheet = package.Workbook.Worksheets.Add(reportName);

                            int totalRows = data.Count();
                            int firstRow = 1;
                            int secondRow = 2;
                            int i = 1;
                            foreach (System.Reflection.PropertyInfo prop in properties_info)//Adding Headers
                            {
                                worksheet.Cells[firstRow, i].Value = prop.Name;
                                i++;
                            }
                            foreach (var p in data)//Adding actual data rows.
                            {
                                int j = 1;
                                foreach (System.Reflection.PropertyInfo prop in properties_info)
                                {
                                    worksheet.Cells[secondRow, j].Value = prop.GetValue(p, null);
                                    j++;
                                }
                                secondRow++;
                            }
                            string firstRowAllColumnsAddress = "A1:Y1";//worksheet.Cells[1, 1, 1, 24]
                            worksheet.Cells[firstRowAllColumnsAddress].Style.Font.Bold = true;
                            worksheet.Cells.AutoFitColumns();
                            await Task.Run(() => { excelData = package.GetAsByteArray(); });
                        }
                    }
                }
                catch (Exception e)
                {
                    throw (e);
                }
                return excelData;
            }

看来您唯一的问题是检索由[Custom(Export = true)]注释的PropertyInfos 您可以通过以下方式实现:

var exportedProps = type_info.GetProperties()
    .Where(p => p.PropertyType.GetCustomAttribute<CustomAttribute>()?.Export == true)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM