0

我正在尝试将多个网格视图导出到一个工作簿中的多个 excel 表中,我查看了很多示例,但还没有找到一个非常有效的示例。我从一个有 4000 多条记录的存储过程中获取数据。我会在单独的网格视图上显示数据,然后使用一个按钮将其全部导出到一个工作簿

当我尝试对其进行测试时,我在sda.Fill(ds) 得到以下信息;

System.Data.dll 中出现“System.Data.SqlClient.SqlException”类型的异常,但未在用户代码中处理

附加信息:执行超时已过期。在操作完成之前超时时间已过或服务器没有响应。

这是我的代码:

using OfficeOpenXml;
using System.Configuration;
using DocumentFormat.OpenXml;
using ClosedXML;


 string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["PostbankConnectionString"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(strConnString);

    SqlCommand command = new SqlCommand("spTest", con) { CommandType = System.Data.CommandType.StoredProcedure };

    SqlDataAdapter sda = new SqlDataAdapter();

    command.CommandTimeout = 300;


    command.Connection = con;
    sda.SelectCommand = command;

    DataSet ds = new DataSet();

    sda = new SqlDataAdapter("spTest", con);

    sda.Fill(ds);
    GridView1.DataSource = ds.Tables[0];
    GridView1.DataBind();
    GridView2.DataSource = ds.Tables[1];
    GridView2.DataBind();
    GridView3.DataSource = ds.Tables[2];
    GridView3.DataBind();
    GridView4.DataSource = ds.Tables[3];
    GridView4.DataBind();
    GridView5.DataSource = ds.Tables[4];
    GridView5.DataBind();
    con.Close();


}
protected void Button1_Click(object sender, System.EventArgs e)
{


    SqlConnection con = new SqlConnection(strConnString);

    SqlCommand command = new SqlCommand("spTest", con) { CommandType = System.Data.CommandType.StoredProcedure };

    SqlDataAdapter sda = new SqlDataAdapter();


    command.Connection = con;
    sda.SelectCommand = command;

    DataSet ds = new DataSet();

    sda = new SqlDataAdapter("spTest", con);


    sda.Fill(ds);
    if (ds.Tables.Count > 0)
    {
        MemoryStream ms = new MemoryStream();

        using (ExcelPackage package = new ExcelPackage(ms))
        {
            foreach (DataTable table in ds.Tables)
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
                worksheet.Cells["A1"].LoadFromDataTable(table, true);
            }
            Response.Clear();
            package.SaveAs(Response.OutputStream);
            Response.AddHeader("content-disposition", "attachchment; filename=Example.xlxs");
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";
            Response.End();
        }
    }
}

}

4

1 回答 1

0

您是否尝试过在 Button1_Click 事件上设置 command.CommandTimeout = 300 以及我无法在您的代码中看到它,或者您遇到的错误是在 Page_Load 事件本身上?尝试将超时时间也增加到 600,看看它是否有效


如果上述方法都不起作用,那么您现在可以尝试通过添加 where 子句来稍微更改您的 sp,这样它就不再是 4000 行,而是仅提供 10 行或其他内容,然后执行您的代码。这样,如果它正确执行,那么至少您可以放心,由于返回的行数更多,您会遇到异常。但是,如果您这样做仍然面临同样的问题,那么在建立连接或其他方面可能有问题。

于 2019-03-13T17:58:53.013 回答