weixin_33725722 2017-06-12 11:03 采纳率: 0%
浏览 319

使用Ajax导出Excel

I have a this code for excel export from database using MVC.

This code working on Index view but if the code in different ActionResult with parameters ( ajax post data ) not working. I can get values using ajax, I can create DataTable from database, datatable can write to excel but not downloading.

Using ClosedXML for excel export.

What can I do for it ?

Thanks for your help.

 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();
                    }
                }
            }
        }
    }
}
  • 写回答

2条回答 默认 最新

  • weixin_33737774 2017-06-13 02:43
    关注

    Hi you can return a stream inorder to download the file in response using the stream

    Here is the example:

      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 method:

    public MemoryStream GetStream(XLWorkbook excelWorkbook)
            {
                MemoryStream fs = new MemoryStream();
                excelWorkbook.SaveAs(fs);
                fs.Position = 0;
                return fs;
            }
    

    Source: http://surajpassion.in/create-an-excel-file-using-closedxml/

    Hope it will solve your problem.

    Thanks

    Karthik

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值