c# - 我如何使用 EPPlus 将子对象导出为 Excel

标签 c# .net excel export-to-excel epplus

我正在使用 EPPlus 帮助我将数据导出为 excel。我仍在学习如何正确导出数据,但不知何故,我无法导出包含所有子对象的对象。

ParentObject
    public string A;
    public string B;
    public ChildObject ChildObject;

ChildObject
    public string C;
    public string D;

所以我希望我导出的 excel 看起来像

A        B        C        D
aa1      bb1      cc1      dd1
aa2      bb2      cc2      dd2
aa3      bb3      cc3      dd3

这就是我当前的实现方式

public void CreateExcel(IEnumerable<T> dataCollection, string fullyQualifiedFileName, string worksheetName)
    {
        using (var package = new ExcelPackage(new FileInfo(fullyQualifiedFileName)))
        {
            var worksheet =
                package.Workbook.Worksheets.FirstOrDefault(excelWorksheet => excelWorksheet.Name == worksheetName) ??
                package.Workbook.Worksheets.Add(worksheetName);

            var membersToInclude = typeof(T)
                .GetMembers(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => Attribute.IsDefined(p, typeof(ExcelUtilityIgnoreAttribute)) == false
                            || p.GetCustomAttribute<ExcelUtilityIgnoreAttribute>().IsIgnored == false)
                .ToArray();

            worksheet.Cells["A1"].LoadFromCollection(dataCollection, true, OfficeOpenXml.Table.TableStyles.None,
                BindingFlags.Public, membersToInclude);

            package.Save();
        }
    }

我尝试通过 expando 对象使用 Microsoft 泛型,但 EPPlus 无法与泛型一起使用,有没有一种方法可以导出带有子对象的对象?

还有:还有其他我可以使用的库吗?

最佳答案

没有可以做到这一点的原生函数。很难提出通用的东西,因为它需要大量的假设。应该自动导出哪些属性类型与应该将哪些属性类型视为子节点并导出或扩展 ITS 属性。但是如果你想出它是从那里开始的基本树遍历。

以下是我从类似任务中改编的内容。在这里,我假设任何 string 或没有属性的数据类型都被视为用于导出的 value 类型 (int, double 等)。但是很容易根据需要进行调整。我把它放在一起所以它可能没有完全优化:

public static void ExportFlatExcel<T>(IEnumerable<T> dataCollection, FileInfo file, string worksheetName)
{
    using (var package = new ExcelPackage(file))
    {
        var worksheet =
            package.Workbook.Worksheets.FirstOrDefault(excelWorksheet => excelWorksheet.Name == worksheetName) ??
            package.Workbook.Worksheets.Add(worksheetName);

        const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
        var props = typeof (T).GetProperties(flags);

        //Map the properties to types
        var rootTree = new Branch<PropertyInfo>(null);

        var stack = new Stack<KeyValuePair<PropertyInfo, IBranch<PropertyInfo>>>(
            props
                .Reverse()
                .Select(pi =>
                    new KeyValuePair<PropertyInfo, IBranch<PropertyInfo>>(
                        pi
                        , rootTree
                        )
                )
            );

        //Do a non-recursive traversal of the properties
        while (stack.Any())
        {
            var node = stack.Pop();
            var prop = node.Key;
            var branch = node.Value;

            //Print strings
            if (prop.PropertyType == typeof (string))
            {
                branch.AddNode(new Leaf<PropertyInfo>(prop));
                continue;
            }

            //Values type do not have properties
            var childProps = prop.PropertyType.GetProperties(flags);
            if (!childProps.Any())
            {
                branch.AddNode(new Leaf<PropertyInfo>(prop));
                continue;
            }

            //Add children to stack
            var child = new Branch<PropertyInfo>(prop);
            branch.AddNode(child);

            childProps
                .Reverse()
                .ToList()
                .ForEach(pi => stack
                    .Push(new KeyValuePair<PropertyInfo, IBranch<PropertyInfo>>(
                        pi
                        , child
                        )
                    )
                );
        }

        //Go through the data
        var rows = dataCollection.ToList();
        for (var r = 0; r < rows.Count; r++)
        {
            var currRow = rows[r];
            var col = 0;

            foreach (var child in rootTree.Children)
            {
                var nodestack = new Stack<Tuple<INode, object>>();
                nodestack.Push(new Tuple<INode, object>(child, currRow));

                while (nodestack.Any())
                {
                    var tuple = nodestack.Pop();
                    var node = tuple.Item1;
                    var currobj = tuple.Item2;

                    var branch = node as IBranch<PropertyInfo>;
                    if (branch != null)
                    {
                        currobj = branch.Data.GetValue(currobj, null);

                        branch
                            .Children
                            .Reverse()
                            .ToList()
                            .ForEach(cnode => nodestack.Push(
                                new Tuple<INode, object>(cnode, currobj)
                                ));

                        continue;
                    }

                    var leaf = node as ILeaf<PropertyInfo>;
                    if (leaf == null)
                        continue;

                    worksheet.Cells[r + 2, ++col].Value = leaf.Data.GetValue(currobj, null);

                    if (r == 0)
                        worksheet.Cells[r + 1, col].Value = leaf.Data.Name;
                }
            }
        }

        package.Save();
        package.Dispose();
    }
}

假设您将这些作为结构:

#region Classes

public class Parent
{
    public string A { get; set; }
    public Child1 Child1 { get; set; }
    public string D { get; set; }
    public int E { get; set; }
    public Child2 Child2 { get; set; }
}

public class Child1
{
    public string B { get; set; }
    public string C { get; set; }
}

public class Child2
{
    public Child1 Child1 { get; set; }
    public string F { get; set; }
    public string G { get; set; }
}

#endregion

#region Tree Nodes

public interface INode { }

public interface ILeaf<T> : INode
{
    T Data { get; set; }
}

public interface IBranch<T> : ILeaf<T>
{
    IList<INode> Children { get; }
    void AddNode(INode node);
}

public class Leaf<T> : ILeaf<T>
{
    public Leaf() { }

    public Leaf(T data) { Data = data; }

    public T Data { get; set; }
}

public class Branch<T> : IBranch<T>
{
    public Branch(T data) { Data = data; }

    public T Data { get; set; }

    public IList<INode> Children { get; } = new List<INode>();

    public void AddNode(INode node)
    {
        Children.Add(node);
    }
}

#endregion

这是一个测试:

[TestMethod]
public void ExportFlatTest()
{
    var list = new List<Parent>();

    for (var i = 0; i < 20; i++)
        list.Add(new Parent
        {
            A = $"A-{i}",
            D = $"D-{i}",
            E = i*10,
            Child1 = new Child1
            {
                B = $"Child1-B-{i}",
                C = $"Child1-C-{i}",
            },
            Child2 = new Child2
            {
                F = $"F-{i}",
                G = $"G-{i}",
                Child1 = new Child1
                {
                    B = $"Child2-Child1-B-{i}",
                    C = $"Child2-Child1-C-{i}",
                }
            }
        });

    var file = new FileInfo(@"c:\temp\flat.xlsx");
    if (file.Exists)
        file.Delete();

    TestExtensions.ExportFlatExcel(
        list
        , file
        , "Test1"
        );
}

会给你这个:

enter image description here

关于c# - 我如何使用 EPPlus 将子对象导出为 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48828850/

相关文章:

c# - 是否可以仅在扩展内部满足条件时才调用方法?

c# - 使用 Interop 从 excel 获取最后一个非空列和行索引

vba - 使用 VBA 在 Excel 中整理数据

c# - DistinctBy,但忽略null/empty

c# - 使用 NodaTime(或替代方法)比较期间的最佳方法

c# - 在 .resx 中将图像存储为 byte[] 而不是 Bitmap

c# - 如何在 ImageButton 单击时将 css 样式分配给 gridview 行?

asp.net - 如何通过ConfigurationManager找到配置文件位置?

c# - 在 C# 中使用 LinkLabel 超链接电子邮件地址

excel - 为什么错误处理例程中的消息被打印两次?