今天晚上开始测试,以前做过一次,但是很不完美。
大致代码如下:
private void excel_btn_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer= true;
Response.Charset="GB2312";
string str =star_text.Text.Trim()+"--"+end_text.Text.Trim(); //设置文件名
Response.AppendHeader("Content-Disposition","attachment;filename="+str+".xls");
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);
MyDataGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
如果有格式转化问题,在ItemDataBound事件中写:
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//这里是设置第2列为文本类型(如 0123 导入excel时保证是0123而不是123)
e.Item.Cells[2].Attributes.Add("style","vnd.ms-excel.NumberFormat:@");
//这里设置有关货币的.(如199.999999这样的数据导入为¥200.00)
e.Item.Cells[3].Attributes.Add("style","vnd.ms-excel.numberformat:¥#,###.00");
}
导入excel后的效果:
http://www.cnblogs.com/zhangzs8896/gallery/image/6127.html