任何想法如何从数据库中更快地下载excel文件?
应按下按钮。我尝试使用以下代码:
SqlConnection connSql = new SqlConnection(Generic);
DataSet ds = new DataSet();
SqlCommand cmdSql = new SqlCommand();
cmdSql.Connection = connSql;
cmdSql.CommandType = System.Data.CommandType.StoredProcedure;
cmdSql.CommandText = "sp_GetDetails";
cmdSql.Parameters.Add(new SqlParameter("@pageIndex", 0));
cmdSql.Parameters.Add(new SqlParameter("@pageSize",rowcount));
cmdSql.Parameters.Add(new SqlParameter("@administratordid", adminid));
connSql.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSql);
da.Fill(ds);
gvDetails.AllowCustomPaging = false;
gvDetails.AllowPaging = false;
gvDetails.DataSource = ds;
gvDetails.DataBind();
connSql.Close();
Response.ClearContent();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.Default;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
Response.ContentType = contentType;
HtmlTextWriter objTW = new HtmlTextWriter(objSW);
gvDetails.RenderControl(objTW);
Response.Write(style);
Response.Write(objSW);
Response.End();
我花了10分钟下载整个文件。我在数据库中的行数是25,000。
请为此建议更快的方法。我一直在尝试不同的代码,但还没有工作。
答案 0 :(得分:2)
使用真实的Excel文件,您可以使用EPPLus生成它,而不是将用户下载和excel尝试显示的表格呈现为HTML。
代码很简单,甚至有一种方法:LoadFromDataTable
:
try {
var pck = new OfficeOpenXml.ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Sheet-Name");
ws.Cells["A1"].LoadFromDataTable(ds.Tables[0], true, TableStyles.Light18);
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
Response.BinaryWrite(pck.GetAsByteArray());
} catch (Exception ex) {
//log error
}
Response.End();