110,499
社区成员
发帖
与我相关
我的任务
分享
protected void Button1_Click(object sender, EventArgs e)
{
string XX = Label1.Text + Label3.Text;
Export("application/ms-excel", XX + "月份采购计划.xls");
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
public static void DGToExcel(Control ctl, string fileName)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename="+fileName);
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
ctl.Page.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
修改一下编码方式解决乱码问题
GridView gv = new GridView();
gv.DataSource = dtError;
gv.DataBind();
gv.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
HttpResponse hResponse = this.Response;
string fileName1 = "新员工格式验证错误统计" + DateTime.Now.ToString("yyyyMMdd");
hResponse.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName1, System.Text.Encoding.UTF8) + ".xls");
hResponse.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
hResponse.ContentType = "application/ms-excel";
this.EnableViewState = false;
StringWriter tw = new StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
gv.RenderControl(hw);
hResponse.Write(tw);
hResponse.End();