gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:33:47 25 4
gpt4 key购买 nike

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

我能够获取所有数据,但单击按钮时这些数据没有导出到 Excel 表。我希望当我点击我的按钮时,它应该将数据导出到 Excel 表中。但目前我的数据显示在 View 上,而不是导出到 Excel Sheet。谁能帮我理解我错过了什么?

Controller :

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>

最佳答案

我不确定您为什么要返回 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);
}

关于c# - 如何使用 ASP.NET MVC 在单击按钮时导出 Excel 工作表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com