C#实现GridView导出Excel
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
namespace DotNet.Utilities
{
/// <summary>
/// Summary description for GridViewExport
/// </summary>
public class GridViewExport
{
public GridViewExport()
{
//
// TODO: Add constructor logic here
//
}
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
//HttpContext.Current.Response.Charset = "utf-8";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
table.GridLines = GridLines.Both; //单元格之间添加实线
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
/// <summary>
/// 导出Grid的数据(全部)到Excel
/// 字段全部为BoundField类型时可用
/// 要是字段为TemplateField模板型时就取不到数据
/// </summary>
/// <param name="grid">grid的ID</param>
/// <param name="dt">数据源</param>
/// <param name="excelFileName">要导出Excel的文件名</param>
public static void OutputExcel(GridView grid, DataTable dt, string excelFileName)
{
Page page = (Page)HttpContext.Current.Handler;
page.Response.Clear();
string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(excelFileName));
page.Response.AddHeader("Content-Disposition", "attachment:filename=" + fileName + ".xls");
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.Charset = "utf-8";
StringBuilder s = new StringBuilder();
s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>");
int count = grid.Columns.Count;
s.Append("<table border=1>");
s.AppendLine("<tr>");
for (int i = 0; i < count; i++)
{
if (grid.Columns[i].GetType() == typeof(BoundField))
s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");
//s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");
}
s.Append("</tr>");
foreach (DataRow dr in dt.Rows)
{
s.AppendLine("<tr>");
for (int n = 0; n < count; n++)
{
if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField))
s.Append("<td>" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "</td>");
}
s.AppendLine("</tr>");
}
s.Append("</table>");
s.Append("</body></html>");
page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString()));
page.Response.End();
}
}
}
C#实现GridView导出Excel的更多相关文章
- Asp.net Gridview导出Excel
前台页面放一个GridView什么的就不说了,要注意的是在 <%@ Page Language="C#" AutoEventWireup="true" C ...
- GridView导出Excel的超好样例
事实上网上有非常多关于Excel的样例,可是不是非常好,他们的代码没有非常全,读的起来还非常晦涩.经过这几天的摸索,最终能够完毕我想要导出报表Excel的效果了.以下是我的效果图. 一.前台的页面图 ...
- ASP.NET gridview导出excel,防止繁体产生有乱码的方式
//1.先引用比如 : using System; using System.Collections.Generic; using System.Linq; using System.Web; usi ...
- GridView导出excel格式问题
在导出的点击事件中,代码如下: //指定导出对应单元格为文本样式 string style = @"<style> .test { vnd.ms-excel.numberform ...
- C# GridView 导出Excel表
出错1:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内解决方案:在后台文件中重载VerifyRenderingInServerForm方法,如 ...
- GridView导出Excel(中文乱码)
public void OUTEXCEL(string items,string where) { DataSet ds = new StudentBLL().GetTable(items,where ...
- GridView导出Excel
public void OUTEXCEL() { DataSet ds = new GW_T_DemandDAL().GetWzH(GetPersonInfoData(UserInfo), Reque ...
- GridView 导出Excel
protected void btnExcel_Click(object sender, EventArgs e) { ) { ExportGridViewForUTF8(GridView1, Dat ...
- C#通过gridview导出excel
[CustomAuthorize] public FileResult ExportQuestionCenterExcel(SearchBaseQuestion search) ...
随机推荐
- python之字符串详解2
逻辑判断字符串类型,返回布尔值 1. islower 描述:判断所有字符是否为小写 语法: def islower(self): # real signature unknown; restored ...
- java 非缓冲与缓冲数据写入比较
//非缓冲计时package com.swust; import java.io.*; /* *功能:创建一个程序,写10000个随机双精度的数到一个文件中,同时测试运用缓冲和非缓冲技术 * 进行这种 ...
- liunx下search文件内容的几种方式
第一种.使用vim来search内容 /regex_word,从上到下匹配 ?regex_word,从下到上匹配 n是获取下一个匹配字符串,N是获取上一个匹配字符串. 第二种.使用grep命令 gre ...
- Javascript面对对象. 第一篇
Javascript,有两个种开发模式: 1.函数式(过程化)2.面对对象(oop),面对对象语言有一个标志,就是类,而通过类可以创建任何多个属性和方法,而Ecmascript没有类的概念,因此它的对 ...
- 【转】Spring源码编译
原文地址: http://www.flyoung.me/2013/08/02/springcodecompile/ 参考资料: https://github.com/spring-projects/s ...
- 什么是Git?
其实我在写这篇随笔的时候连Git是什么都不知道,只是听说过,也注册了一个GitHub的账号,但并不会玩. 我也是查看了半天的网页才明白一个大概,但我觉得以后肯定会经常用到它. 简单的来说, Git 是 ...
- 每天一个Linux命令(04)--mkdir命令
Linux mkdir 命令用来创建指定的名称的目录,要求创建目录的用户在当前目录中具有写权限,并且指定的目录名不能是当前目录中已有的目录. 1.命令格式: mkdir [选项]目录 2.命令功能: ...
- AlloyTouch之无限循环select插件
写在前面 当滚动的内容很多,比如闹钟里设置秒,一共有60项.让使用者从59ms滚回01ms是一件很痛苦的事情,所以: 在列表项太多的情况下,我们希望能够有个无限循环的滚动.00ms和01ms是无缝链接 ...
- 在Vue中通过自定义指令获取元素
vue.js 是数据绑定的框架,大部分情况下我们都不需要直接操作 DOM Element,但在某些时候,我们还是有获取DOM Element的需求的: 在 vue.js 中,获取某个DOM Eleme ...
- 前端性能监控:window.performance
window.performance 是W3C性能小组引入的新的API,目前IE9以上的浏览器都支持.一个performance对象的完整结构如下图所示: memory字段代表JavaScript对内 ...