如何使用epplus将我的html表写入excel文件

时间:2014-04-01 08:33:51

标签: html asp.net-mvc excel epplus

所以我在这里尝试做的是使用epplus将一个简单的html表写入xlsx(excel)文件。我到目前为止的代码是

控制器:

public void saveToExcel(string tbl)
    {
        using (ExcelPackage p = new ExcelPackage())
        {
            p.Workbook.Worksheets.Add("demo");
            ExcelWorksheet ws = p.Workbook.Worksheets[1]; 


            ws.Name = "Demo";

            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
            Response.BinaryWrite(p.GetAsByteArray());
        }

    }

现在这会创建一个空的工作簿。而我现在想要做的就是把这张桌子写在我的

查看:

<Table id="tbl" name="tbl">
                <tr>
                    <td>
                        Title 1
                    </td>
                    <td >
                        Title 1
                    </td>
                    <td>
                        Title 1
                    </td>
                </tr>
                <tr>
                    <td >
                        Row 1
                    </td>
                    <td>
                        Row 1
                    </td>
                    <td>
                        Row 1
                    </td>
                </tr>
                <tr>
                    <td >
                        Row 2
                    </td>
                    <td>
                        Row 2
                    </td>
                    <td>
                        Row 2
                    </td>
                </tr>
                <tr>
                    <td >
                        Row 2
                    </td>
                    <td>
                        Row 2
                    </td>
                    <td>
                        Row 2
                    </td>
                </tr>
            </table>

        @Html.ActionLink("saveToExcel", "saveToExcel")

到工作簿。但我只是不知道如何以及从哪里开始。

感谢任何正确方向的指示。

1 个答案:

答案 0 :(得分:5)

我猜: 首先,您必须将HTML表转换为.NET Datatable 这可以在Convert Table

找到

接下来使用此代码(考虑到您创建的数据表称为“数据”:

        Dim attachment As String = "attachment; filename=MyExcelPage.xlsx"

        Dim epackage As ExcelPackage = New ExcelPackage
        Dim excel As ExcelWorksheet = epackage.Workbook.Worksheets.Add("ExcelTabName")
        excel.Cells("A1").LoadFromDataTable(data, True)

        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.ClearHeaders()
        HttpContext.Current.Response.ClearContent()
        HttpContext.Current.Response.AddHeader("content-disposition", attachment)
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

        HttpContext.Current.Response.BinaryWrite(epackage.GetAsByteArray())

        HttpContext.Current.Response.End()
        epackage.Dispose()