protected void btnExport_Click(object sender, ImageClickEventArgs e)
{
string sql = "select * from Customer";
DataTable dt = DBHelper.GetTable(sql);
gvwExport.DataSource = dt;
gvwExport.DataBind();
string style = @"<style> .text { mso-number-format:\@; } </script> ";
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode("客户档案", System.Text.Encoding.UTF8) +
DateTime.Now.ToString("yyMMdd") + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvwExport.RenderControl(htw);
Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>");
Response.Write(style);
string sads = sw.ToString();
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{ }
控制导出文件的格式,免除Excel科学计数等麻烦
protected void gvwExport_RowDataBound(object sender, GridViewRowEventArgs e)
{
//1) 文本:vnd.ms-excel.numberformat:@
//2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
//3) 数字:vnd.ms-excel.numberformat:#,##0.00
//4) 货币:vnd.ms-excel.numberformat:¥#,##0.00
//5) 百分比:vnd.ms-excel.numberformat: #0.00%
//white-space:normal 自动换行
//border-right:1px #CCCCCC groove;border-bottom:1px #CCCCCC groove;
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (e.Row.RowType == DataControlRowType.DataRow)
e.Row.Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
}
}