asp.net中GridView导出数据
时间:2010-12-31 来源:魏斌
///模式化特殊元素将服务控件改为Literal使其可以输出
public void PrepareGridViewForExport(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(ImageButton))
{
l.Text = "图片";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}
///导出方法
///FileType导出类型 application/excel导出excel文件word导出为word文档
///FileName 文件名称
public void Export(string FileType, string FileName)
{
string style = @"<style>.text{mso-number-format:@}</script>";//导入到excel时,保存表里数字列中前面存在的 0 .
PrepareGridViewForExport(GridView1);//将模版列显示出来
Response.Clear();
Response.Charset = "GB2312 ";
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
this.GridView1.AllowPaging = false;
CultureInfo myCItrad = new CultureInfo("ZH-CN", true);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
this.GridView1.RenderControl(htw);
Response.Write(style);
Response.Write(sw.ToString());
//Response.Write(dt.ToString());
Response.End();
}