如何使用ASP.NET MVC在单击按钮上导出Excel工作表中的数据

时间:2017-08-03 20:16:52

标签: c# asp.net asp.net-mvc excel office-interop

我正在尝试在ASP.NET MVC中单击按钮导出数据。我写了一个JSONResult ExportDataInExcel()类,在这里我编写了代码来导出我从MyService得到的数据。

我能够获取所有数据,但是这些数据不会在按钮点击时导出到Excel工作表。我希望当我点击我的按钮时,它应该将数据导出到Excel工作表。但目前我的数据显示在View上,而不是导出到Excel Sheet。请问任何人能帮助我理解我失踪的是什么吗?

控制器:

public JsonResult ExportDataInExcel(int A, int B, string C)
{
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-disposition", "attachment; filename=Test.xls");
    Response.Charset = "";

    MyService.ServiceInfoClient objMyService = new MyService.ServiceInfoClient();

    System.IO.StringWriter stringWriter = new System.IO.StringWriter();
    HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

    GridView ExcelGrid = new GridView();
    ExcelGrid.DataSource = from data in objMyService.ExportTestData(lId,wId,cid)
        select new
        {
            A=data.a,
            B=data.b,
            C=data.c,
            D=data.d,
            E=data.e,
            F=data.f,
            G=data.g
        };
    ExcelGrid.DataBind();
    ExcelGrid.HeaderStyle.Font.Bold = true;
    ExcelGrid.HeaderStyle.ForeColor = System.Drawing.Color.White; ;
    ExcelGrid.HeaderStyle.BackColor = System.Drawing.Color.Green;
    ExcelGrid.RenderControl(htmlTextWriter);

    Response.Output.Write(stringWriter.ToString());
    Response.Flush();
    Response.End();

    return Json(ExcelGrid);
}

查看

<script type="text/javascript">
    function ExportTestDet(){
        if ($("#ddl1").val() == '0') {
            alert('Please select');
            return false;
        }

        if ($("#ddl2").val() == '0') {
            alert('Please select');
            return false;
        }

        $.ajax({
            type: 'POST',
            url: '@Url.Action("ExportDataInExcel")',
            datatype: 'JSON',
            data: { LId: $("#ddl1").val(), WID: $("#ddl2").val() },
            success: function (data) {
                $("#DynamicContent").html(data);
                $("#tbl").show();
                alert("Exported");
            },
            error: function (ex) {
                alert('Failed to export data: ' + ex.responseText);
            }
        });
    }
</script>

<div>
    <input type="submit" value="Export Excel" onclick="return ExportTestDet()" />
</div>

2 个答案:

答案 0 :(得分:0)

我不确定你为什么要返回一个JSON字符串,但是期待Excel。

而不是JsonResult,返回一个ActionResult,如下所示:

public ActionResult ExportDataInExcel(int A, int B, string C)
{
    string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    string fileName = "WhateverFile.xlsx";

    // CODE TO GENERATE EXCEL FILE (OR CSV) HERE (I recommend EPPlus)

    // output the file
    var stream = new MemoryStream();
    EPPlusExcelFileYouGenerated.SaveAs(stream); // however you get your generated file to the MemoryStream is fine.

    stream.Position = 0;
    return File(stream, contentType, fileName);
}

答案 1 :(得分:0)

使用Jquery jquery.table2excel.js这将有助于您移植 从html表到excel和table的日期必须是正确格式的head和body 标签和表格ID也必须。