[英]How to save downloaded Excel file data from Data table into application folder in ASP.NET
I want downloaded file into save application folder here I downloaded file as Excel sheet from data table. 我想将文件下载到保存应用程序文件夹中,我从数据表中将文件下载为Excel工作表。 I didn't take path to file download it's directly download from data table and I want to save it in application folder.
我没有下载文件的路径,而是直接从数据表下载,我想将其保存在应用程序文件夹中。 How can I do this?
我怎样才能做到这一点?
My code: 我的代码:
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();
}
}
}
It took a while to make sense of the order of things but removing the call to TransmitFile()
should work. 花了一段时间才能弄清事物的顺序,但删除对
TransmitFile()
的调用应该可以工作。 You're already writing out the file via the MemoryStream
. 您已经通过
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();
}
}
}
If this is a standard MVC controller action then your response is much easier and changes to; 如果这是标准的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");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.