如何将下载的Excel文件数据从Data表保存到ASP.NET

时间:2017-09-22 14:47:36

标签: c# asp.net excel

我想将下载的文件保存到保存应用程序文件夹中我从数据表下载文件作为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();
                }
            }
        } 

1 个答案:

答案 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");
            }
        }
    }