C#读取自定义属性的值

问题描述 投票:0回答:1

我只想导出Export = true的属性。我有另一个方法,该方法将接受任何对象(不仅仅是PlanSetup),将其解包,并将行添加到ExcelWorkBook。我已经设法获取对象的类型,但是要获取“自定义属性”的值是我所努力的地方。我能够将行/列添加到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<ADP.RS.Payroll.Core.Models.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;
            }
c# excel
1个回答
0
投票

[您似乎唯一的问题是检索PropertyInfos,并用[Custom(Export = true)]注释。您可以通过以下方式实现:

var exportedProps = type_info.GetProperties()
    .Where(p => p.PropertyType.GetCustomAttribute<CustomAttribute>()?.Export == true)
© www.soinside.com 2019 - 2024. All rights reserved.