我想将下载的文件保存到保存应用程序文件夹中我从数据表下载文件作为Excel表格。我没有采取文件下载的路径,它直接从数据表下载,我想将其保存在应用程序文件夹中。我怎么能这样做?
我的代码:
public void ExportToExcel(DataSet ds)
{
using (XLWorkbook wb = new XLWorkbook())
{
foreach (DataTable dt in ds.Tables)
{
//Add DataTable as Worksheet.
wb.Worksheets.Add(dt);
}
//Export the Excel file.
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Report.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.TransmitFile(Server.MapPath("~/Files/Report.xlsx"));// I added this but it shows error
Response.Flush();
Response.End();
}
}
}
答案 0 :(得分:0)
需要一段时间来理解事物的顺序,但删除对TransmitFile()
的调用应该有效。您已经通过MemoryStream
。
public void ExportToExcel(DataSet ds)
{
using (XLWorkbook wb = new XLWorkbook())
{
foreach (DataTable dt in ds.Tables)
{
//Add DataTable as Worksheet.
wb.Worksheets.Add(dt);
}
//Export the Excel file.
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Report.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
如果这是一个标准的MVC控制器操作,那么您的响应会更容易并且更改为;
public FileStreamResult ExportToExcel(DataSet ds)
{
using (XLWorkbook wb = new XLWorkbook())
{
foreach (DataTable dt in ds.Tables)
{
//Add DataTable as Worksheet.
wb.Worksheets.Add(dt);
}
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
return FileStreamResult(MyMemoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
}
}