数据Excel方式下载
public void CreateExcel(DataTable dt, string FileName, int pageSize, int pageNum)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.ContentType = "application/ms-excel";
resp.AddHeader("Content-Disposition",
"attachment; filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
this.EnableViewState = false;
string colHeaders = "", Is_item = "";
int i = 0;
//定义表对象与行对象,同时使用DataSet对其值进行初始化
DataRow[] myRow = dt.Select();
//取得数据表各列标题,标题之间以\t分割,最后一个列标题后加回车符
for (i = 0; i < dt.Columns.Count; i++)
{
colHeaders += " " + dt.Columns[i].Caption.ToString() + "\t";
}
colHeaders += "\n";
resp.Write(colHeaders);
//逐行处理数据
int num = dt.Rows.Count > (pageNum + 1) * pageSize ? (pageNum + 1) * pageSize : dt.Rows.Count;
for (int j = pageSize * pageNum; j < num; j++)
{
//在当前行中,逐列取得数据,数据之间以\t分割,结束时加回车符\n
for (i = 0; i < dt.Columns.Count; i++)
{
Is_item += " " + dt.Rows[j][i].ToString() + "\t";
}
Is_item += "\n";
resp.Write(Is_item);
Is_item = "";
}
//写缓冲区中的数据到HTTP头文件中
resp.End();
}
Gridview 这样下载Gridview里面不能有模板列
string style = @"<style> .text { mso-number-format:\@; } </script> ";
Resposnse.ClearContent();
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.AppendHeader("content-disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode("SAPIvr邀请",
System.Text.Encoding.UTF8) + ".xls\"");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
GridView1.RenderControl(htw);
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步