无法将多个GridView导出到多个Excel



我试图在一个工作簿中向几张excel床单导出几个GridViews,我看了许多示例,但还没有发现一个非常有用的示例。我正在从拥有4000多个记录的存储过程中获取数据。我将在单独的GridViews上显示数据,然后使用一个按钮将其全部导出到一个工作簿

当我尝试测试它时,我会在 sda.fill(ds); 中获得以下内容:

类型" system.data.sqlclient.sqlexception"的例外发生在system.data.dll中,但在用户代码中未处理

其他信息:执行超时到期。超时期 在完成操作之前已通过,或者服务器不是 响应。

这是我的代码:

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();
        }
    }
}

}

您是否尝试过设置命令。本身?尝试将超时也增加到600,看看它是否有效


如果以上都没有工作,那么您现在可以尝试的是通过添加子句的位置而不是4000行,它仅提供10行或其他内容,然后执行您的代码,从而更改SP。这样,如果它正确执行,那么至少您可以确保由于返回的行数量数量增加,因此您会得到异常。但是,如果您仍然可以通过此操作面对同一问题,那么建立连接或其他问题也许是错误的。

最新更新