使用EPPlus将多个数据集导出到单个Excel工作表

时间:2017-01-10 18:49:27

标签: excel vb.net epplus

我无法找到有关如何使用EPPlus库将多个数据集/表导出到单个Excel工作表的示例。当我运行代码时,它返回恰好是最后一组的一组。我在以下代码中做错了什么?谢谢!

Dim dSets as DataSets
Dim dGrid as DataGrid
Dim dTable as DataTable
Dim sheet as String
sheet = "DumpSets"
Dim attachment as String
attachment = "attachment; filename=" + sheet + ".xlsx"
Dim xlPack as ExcelPackage = New ExcelPackage()
Dim ws as ExcelWorksheet = xlPack.Workbook.Worksheets.Add(sheet)
Response.Clear()
Response.AddHeader("content-disposition", attachment)
Response.Charset = ""

For each dTable in dSets.Tables
    dGrid = New DataGrid
    Me.EnableViewState = False

    dGrid.DataSource = dTable
    ws.Cells(1, 1).LoadFromDataTable(dGrid.DataSource, True)

    dGrid.DataBind()
Next

Response.BinaryWrite(xlPack.GetAsByteArray())
Response.End()

1 个答案:

答案 0 :(得分:2)

正如@Blackwood已经提到的,你总是在同一个地方添加数据。

所以它应该是这样的:

Dim cnt As Integer = 1

For each dTable in dSets.Tables
    dGrid = New DataGrid
    Me.EnableViewState = False

    dGrid.DataSource = dTable
    ws.Cells(1, cnt).LoadFromDataTable(dGrid.DataSource, True)

    dGrid.DataBind()

    cnt = (cnt + 1)
Next

您还可以将每个数据集添加到自己的工作表中。

Dim cnt As Integer = 1
For Each dt As DataTable In dSets.Tables
    Dim ws As ExcelWorksheet = xlPack.Workbook.Worksheets.Add(("Sheet " + cnt))
    ws.Cells(1, 1).LoadFromDataTable(dGrid.DataSource, True)
    cnt = (cnt + 1)
Next