本文实例展示了C#使用RenderControl将GridView控件导出到EXCEL的方法,是非常实用的一个功能,分享给大家供大家参考。具体如下:
主要功能代码如下:
// 把GridView输出到Excel文件
private void ExportExcel(GridView gridView, string title, string title2, string fileName)
{
int nHideCols = 0;
//如果不想输出出某列,将Visible设为false即可
for (int i = 0; i < gridView.Columns.Count; i++)
{
if (gridView.Columns[i].HeaderText == "设备状态")
{
gridView.Columns[i].Visible = false;
gridView.Columns[i].ControlStyle.Width = 0;
nHideCols = 1;
break;
}
}
//设定显示字符集
Response.Charset = "utf-8";
//设定内容字符集
Response.ContentEncoding = Encoding.GetEncoding("utf-8");
//设定文件名
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace('+', '_').Replace('-', '_'));
//设定文件类型 也可以是application/ms-word,也可以是text/html(字符集设为gb2312)
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
using (StringWriter tw = new StringWriter())
{
using (HtmlTextWriter hell = new HtmlTextWriter(tw))
{
gridView.AllowPaging = false;
gridView.RenderControl(hell);
string s = tw.ToString();
s = s.Replace("rn", "");
int index = s.IndexOf("" + title + " " +
"" + title2 + " ";
//使用Index来判断是否存在数据,当然也可以用gridView.Rows.Count来判断
if (index != -1)
{
//有数据的
s = s.Insert(index, head);
}
else
{
//没有数据的时候
s = "本文实例代码备有较为详尽的注释,应该不难理解。希望本文实例对大家C#程序设计有所帮助。



