我正在尝试将数据库中的所有用户导出到excel文件。
运行此代码并调试后,我没有遇到任何错误,并且LetsExcelAll()方法一直处于运行状态。不知道我在想什么。代码运行完毕后,不会遇到任何错误,也不会开始下载。
控制器:
public void LetsExcelAll()
{
try
{
var userRepo = new UsersRepository();
XLWorkbook wb = null;
wb = userRepo.DownloadUsers();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Users.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
catch(Exception ex)
{
throw ex;
}
}
REPO:
public XLWorkbook DownloadUsers()
{
try
{
if (thisConnection.State == ConnectionState.Closed)
thisConnection.Open();
MySqlCommand download = thisConnection.CreateCommand();
download.CommandText = UserQueries.DownloadUsers;
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
sda.SelectCommand = download;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt, "ALL_Users");
ws.Columns().AdjustToContents();
ws.Columns().Style.Alignment.SetWrapText();
return wb;
}
}
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
thisConnection.Close();
}
}
视图:(如何调用该方法)
$("#downloadAllUsers").click(function () {
$.post("/Users/LetsExcelAll")
});
答案 0 :(得分:1)
您不能直接返回文件作为jQuery.post()
方法的响应。必须将文件以字节数组的形式存储在TempData
或Session
状态下,并将其传递给标记为HttpGetAttribute
的另一个控制器,以便用户下载文件。
要执行以下步骤:
1)更改LetsExcelAll
方法以返回包含文件名的JsonResult
并将MemoryStream
的输出存储在TempData
/ Session
变量内,并具有如下所示的某些键
[HttpPost]
public ActionResult LetsExcelAll()
{
try
{
var userRepo = new UsersRepository();
XLWorkbook wb = null;
wb = userRepo.DownloadUsers();
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
// set stream to starting position
MyMemoryStream.Position = 0;
// store file contents inside TempData
TempData["ExcelFile"] = MyMemoryStream.ToArray();
}
// return file name as JSON data
return new JsonResult() { Data = new { FileName = "Users.xlsx", Status = "Success" } };
}
catch(Exception ex)
{
throw ex;
}
return new JsonResult() { Data = new { Status = "Nothing" } };
}
2)在AJAX window.location
响应中设置POST
以将文件名作为使用GET
的操作方法名称的查询字符串参数(假设downloadAllUsers
是一个按钮元素)
$("#downloadAllUsers").click(function () {
$.post("/Users/LetsExcelAll", function(data) {
if (data.Status == "Success") {
window.location = '/Users/DownloadFile?fileName=' + data.FileName;
}
});
});
3)使用文件名作为输入参数,用HttpGetAttribute
创建一个新控制器,并从中返回FileResult
。
[HttpGet]
public ActionResult DownloadFile(string fileName)
{
if (TempData["ExcelFile"] != null)
{
var data = TempData["ExcelFile"] as byte[];
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(data, contentType, fileName);
}
else
{
// if TempData messing up, return nothing
return new EmptyResult();
}
}
从这一点来看,文件下载应该可以正常工作。
相关问题: