Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Ajax导出Excel_Ajax_Asp.net Mvc_Excel_Razor - Fatal编程技术网

用Ajax导出Excel

用Ajax导出Excel,ajax,asp.net-mvc,excel,razor,Ajax,Asp.net Mvc,Excel,Razor,我有一个使用MVC从数据库导出excel的代码 这段代码在索引视图上工作,但是如果代码在不同的ActionResult中使用参数ajax post数据,则该代码不工作。我可以使用ajax获取值,我可以从数据库创建DataTable,DataTable可以写入excel,但不能下载 使用ClosedXML进行excel导出 我能为它做些什么 谢谢你的帮助 string constr =ConfigurationManager.ConnectionStrings["constr"].Connect

我有一个使用MVC从数据库导出excel的代码

这段代码在索引视图上工作,但是如果代码在不同的ActionResult中使用参数ajax post数据,则该代码不工作。我可以使用ajax获取值,我可以从数据库创建DataTable,DataTable可以写入excel,但不能下载

使用ClosedXML进行excel导出

我能为它做些什么

谢谢你的帮助

 string constr =ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

using (SqlConnection con = new SqlConnection(constr))
{
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                using (XLWorkbook wb = new XLWorkbook())
                {
                    wb.Worksheets.Add(dt, "Customers");

                    Response.Clear();
                    Response.Buffer = true;
                    Response.Charset = "";
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
                    using (MemoryStream MyMemoryStream = new MemoryStream())
                    {
                        wb.SaveAs(MyMemoryStream);
                        MyMemoryStream.WriteTo(Response.OutputStream);
                        Response.Flush();
                        Response.End();
                    }
                }
            }
        }
    }
}

您好,您可以返回一个流,以便使用流下载文件作为响应

以下是一个例子:

  DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Country",typeof(string)) });
            dt.Rows.Add(1, "C Sharp corner", "United States");
            dt.Rows.Add(2, "Suraj", "India");
            dt.Rows.Add(3, "Test User", "France");
            dt.Rows.Add(4, "Developer", "Russia");
            //Exporting to Excel
            string folderPath = "C:\\Excel\\";
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            //Codes for the Closed XML
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt, "Customers");

                //wb.SaveAs(folderPath + "DataGridViewExport.xlsx");
                string myName = Server.UrlEncode("Test" + "_" + DateTime.Now.ToShortDateString() +          ".xlsx");
                MemoryStream stream = GetStream(wb);// The method is defined below
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=" + myName);
                Response.ContentType = "application/vnd.ms-excel";
                Response.BinaryWrite(stream.ToArray());
                Response.End();
            }
GetStream方法: 资料来源:

希望它能解决你的问题

谢谢


Karthik

HelloÖmür请尝试下面的代码,而不是使用ajax post方法。您还可以使用location.href传递参数

 <input type="button" value="Export" id="btnExport"/>

 <script type="text/javascript">
   $("#btnExport").click(function f(){
    location.href = '@Url.Action("Export","ControllerName")';
});
</script>
 <input type="button" value="Export" id="btnExport"/>

 <script type="text/javascript">
   $("#btnExport").click(function f(){
    location.href = '@Url.Action("Export","ControllerName")';
});
</script>
  public void Export()
    { 
string constr=ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
{
    using (SqlDataAdapter sda = new SqlDataAdapter())
    {
        cmd.Connection = con;
        sda.SelectCommand = cmd;
        using (DataTable dt = new DataTable())
        {
            sda.Fill(dt);
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt, "Customers");

                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();
                }
            }
        }
    }
}
}
}