如何从C#中导出List<object>或IEnumerable的数据到Excel(MS OpenXml)?

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

我想导出一个 List<dynamic>IEnumerable 使用微软的Open XML库将其转换为Excel文件。

库。https:/github.comOfficeDevOpen-XML-SDK。

类似请求的例子。https:/www.codeproject.comArticles692121Csharp-Export-data-to-Excel-using-OpenXML-librarie

上面的例子工作得很好,但有很多代码之间(到目前为止,工作整洁,但我搜索的优化

但是这个库的文档并没有扩展(或者说没有很多例子),而且我看到的关于如何将数据导出到Excel的例子都是使用的是 DataTableDataset;所以,他们使从的谈话。ListDataTable 以输出 DataTable. 而这似乎是相当复杂的方式,其他库解决更容易。

所以,如果有人能举个例子说明如何快速和通用地导出,那就感激不尽了。

excel asp.net-core openxml openxml-sdk
1个回答
0
投票

顺便说一下,这是我的实现,使用了@mikesknowledgebase的代码(http:/www.mikesknowledgebase.com -- 网页不工作......但至少要给信用:D)

发布所有信息 此处


所以,我把它用于.Net Core 2.2;而打算用该方法导出一个 List<dynamic>Excel.

最后的结果(在最简单的例子中)。

[HttpGet("[action]")]
public FileResult exportExample()
{
    List<dynamic> data = new List<dynamic>();

    data.Add(new { a = 1, b = "HELLO WORLD", c = DateTime.Now });
    data.Add(new { a = 2, b = "TEST", c = 34 });

    // Implementation of Dictionary to limit the columns and the type of the List
    // Works with some standard, and flat files (Not with Dynamic Objects that have multiples levels - Indentation of a dynamic into a property)
    Dictionary<string, Type> columns = new Dictionary<string, Type>();
    columns.Add("a", typeof(int));
    columns.Add("b", typeof(string));
    columns.Add("c", typeof(object)); // Accepts any (Numbers or DateTime)

    string excelContentType;
    var excelStream = CreateExcelFile.CreateExcelStream(data, columns, out excelContentType);

    return File(excelStream, excelContentType, "report.xlsx");
}

我在Mike的类中创建了一些其他方法... ...

方法来获取 List 随着 Dictionary<string, type> 和另一个参数来返回 ContentType

public static byte[] CreateExcelStream<T>(List<T> list, Dictionary<string, Type> columns, out string contentType )
{
    DataSet ds = new DataSet();

    ds.Tables.Add(ListToDataTable(list, columns));
    contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // "application/vnd.ms-excel";

    return CreateExcelStream(ds).fwToByteArray();
}

另一种转换方法: ListDataTable:

public static DataTable ListToDataTable<dynamic>(List<dynamic> list, Dictionary<string, Type> columns)
{
    DataTable dt = new DataTable();

    foreach (var column in columns)
        dt.Columns.Add(new DataColumn(column.Key, GetNullableType(column.Value)));

    foreach (var t in list)
    {
        DataRow row = dt.NewRow();

        ((object)t)
        .GetType()
        .GetProperties()
        .ToList()
        .ForEach(p =>
        {
            if (!IsNullableType(p.PropertyType))
                row[p.Name] = p.GetValue(t, null);
            else
                row[p.Name] = (p.GetValue(t, null) ?? DBNull.Value);
        });
        dt.Rows.Add(row);
    }
    return dt;
}

我加入了一个扩展,以转换 streambyteArray:

public static byte[] fwToByteArray(this Stream stream)
{
    stream.Position = 0;
    byte[] buffer = new byte[stream.Length];

    for (int totalBytesCopied = 0; totalBytesCopied < stream.Length;)
        totalBytesCopied += stream.Read(buffer, totalBytesCopied, Convert.ToInt32(stream.Length) - totalBytesCopied);

    return buffer;
}

剩下的代码还是一样... 这是结果。Example

© www.soinside.com 2019 - 2024. All rights reserved.