string strDate1 = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + strDate1 + ".xls");
//System.Globalization.CultureInfo myCItrad =System.Globalization.CultureInfo.CurrentCulture;
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文
Response.ContentType = "application/ms-excel"; //设置输出文件类型为excel文件。
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
// repeater控件的ID
rptList.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
数字以文本形式导出到excel
<td style="vnd.ms-excel.numberformat:@"><%#Eval("序")%></td>
//DataTable通过gridview导出excel
protected string ExportDataTableToExcel(System.Data.DataTable table)
{
string rf = System.DateTime.Now.ToLongTimeString();
System.Web.UI.WebControls.GridView dgExport = null;
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWrite = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (table.Rows.Count > 0)
{
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "utf-8";
curContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + rf + ".xls");
strWrite = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWrite);
dgExport = new System.Web.UI.WebControls.GridView();
dgExport.DataSource = table.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
int icolms = dgExport.HeaderRow.Cells.Count;
foreach (GridViewRow dg in dgExport.Rows)
{
for (int i = 0; i < icolms; i++)
{
if (dg.Cells[i].Text.Contains("/")||dg.Cells[i].Text.IndexOf('0')==0)
{
dg.Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
}
}
}
dgExport.RenderControl(htmlWriter);
curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>");
curContext.Response.Write(strWrite);
curContext.Response.Flush();
curContext.Response.End();
}
return rf;
}