【问题标题】:Convert table to excel将表格转换为excel
【发布时间】:2014-12-08 14:14:16
【问题描述】:

我想将表中的所有记录写入 Excel 文件。 我的表中有大约 30000 行。

我只能将 20000 行写入 excel。在System out of memory 发生异常之后。

这是我的代码。提前致谢。

using (SqlConnection con = new SqlConnection(strconnection))
{
   using (SqlCommand cmd = new SqlCommand("SELECT  * FROM tbl_ReportwithoutDup"))
   {
        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, "Report1");

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

【问题讨论】:

  • 您在使用 Excel 互操作服务库吗?或者您使用什么库来生成 Excel 文件?
  • 不要在服务器上使用互操作,看这里:stackoverflow.com/a/9569827/351383

标签: c# asp.net sql-server excel


【解决方案1】:

因此,这不是一个完美的解决方案,但由于您使用的是 Web 框架 (asp.net),您可以随时将其全部写入 HTML 表格,然后将响应的内容类型设置为 @ 987654322@。结果是浏览器将默认下载客户端在 Excel 中打开的 CSV 文件。

【讨论】:

  • 我正在使用此代码aspsnippets.com/Articles/…
  • ?好的...我的意思是,如果您愿意,您可以在服务器上使用 Excel 来完成所有工作。而且它可能更节省内存。
  • Paul,你说要写一个 HTML 表格,但你说用户会下载一个 CSV 文件?它是如何工作的?
  • HTML 表被浏览器根据我提到的内容类型设置解释为 CSV 文件。我已经多次成功地做到了这一点。
猜你喜欢
  • 2019-12-12
  • 1970-01-01
  • 2021-05-27
  • 2020-07-19
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 2019-11-03
相关资源
最近更新 更多