创建数据列而不是行

Create Columns of Data Instead of Rows

我想将我的数据按列而不是按行插入 Excel,如下所示:

 ---------------
| Name1 | Name2 |
| Qty1  | Qty2  |
| Qtys1 | Qtys2 |
| Per1  | Per2  |
| Old1  | Old2  |
 ---------------

这是我目前拥有的:

        using (ExcelPackage excel = new ExcelPackage())
        {
            ExcelWorksheet ws;

            ws = excel.Workbook.Worksheets.Add("Chart");

            var table = ws.Cells["B4"].LoadFromCollection(
                dmr,
                false,
                OfficeOpenXml.Table.TableStyles.Light15,
                BindingFlags.Public,
                new MemberInfo[]
                {
                    typeof(DMR).GetProperty("Name"),
                    typeof(DMR).GetProperty("Qty"),
                    typeof(DMR).GetProperty("Qtys"),
                    typeof(DMR).GetProperty("Per"),
                    typeof(DMR).GetProperty("Old")
                });

这当前显示我的数据如下:

 ------------------------------------
| Name1 | Qty1 | Qtys1 | Per1 | Old1 |
| Name2 | Qty2 | Qtys2 | Per2 | Old2 |
 ------------------------------------

是否有设置告诉它处理行而不是列,或者是否需要额外的代码?

不幸的是,没有简单的方法可以使用 EPPlus 以这种方式旋转数据,但是只要数据大小不是太大,以下方法就可以工作:

using (ExcelPackage excel = new ExcelPackage(file))
{
    ExcelWorksheet ws;
    DataTable dt = new DataTable();

    // Get the worksheet
    ws = excel.Workbook.Worksheets["Chart"];

    // Create as many columns as there are rows
    for (int i = 0; i < ws.Dimension.End.Row; i++) {
        dt.Columns.Add(i.ToString());
    }

    // Go through each column and create a new row of data
    for (int i = 1; i <= ws.Dimension.End.Column; i++) {
        var row = dt.NewRow();
        for (int j = 1; j <= ws.Dimension.End.Row; j++) {
            row[j-1] = ws.Cells[j, i].Value;
        }
        dt.Rows.Add(row);
    }
}

请注意,headers 列将只是 1 | 2 | 3 | etc,这可以在第一个 for 循环中更改。