http://www.aspsnippets.com/Articles/Export-GridView-to-Excel-in-ASPNet-with-Formatting-using-C-and-VBNet.aspx

1. HTML 页面

添加GridView控件,编辑要绑定的字段。

添加转换按钮

<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="" CellSpacing="">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" /> <Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Address" HeaderText="Address" />
</Columns>
</asp:GridView> <asp:Button ID="Button1" runat="server" Text="ExportToExcel" OnClick="Button1_Click"/>
</div>

2. 添加需要的命名空间

using System.IO;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;

3. 后台绑定GridView的方法

private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["DemosDatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}

4. 在页面加载的时候,绑定GridView

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

5. 实现GridView的分页--PageIndexChanging事件

 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}

6.把GridView转换成Excel的方法

     protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw); //To Export all pages
GridView1.AllowPaging = false;
this.BindGrid(); GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % == )
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{ cell.BackColor = GridView1.RowStyle.BackColor
}
cell.CssClass = "textmode";
}
} GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}

7. 必须添加的一个事件

public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

转换GridView的内容到Excel里面 ---带有格式的更多相关文章

  1. 将gridview 的数据导出EXCEL

    gridview数据 单击“导出EXCEL”按钮后        1.在上面的代码中,先将gridview绑定到指定的数据源中,然后在button按钮(用来做导出到EXCEL的)的事件中,写入相关的代 ...

  2. ASP.NET中GridView数据导出到Excel

    /// <summary> /// 导出按钮 /// </summary> /// <param name="sender"></para ...

  3. VBA读取word中的内容到Excel中

    原文:VBA读取word中的内容到Excel中 Public Sub Duqu()      Dim myFile As String     Dim docApp As Word.Applicati ...

  4. Android控件GridView之仿支付宝钱包首页带有分割线的GridView九宫格的完美实现

    Android控件GridView之仿支付宝钱包首页带有分割线的GridView九宫格的完美实现 2015-03-10 22:38 28419人阅读 评论(17) 收藏 举报  分类: Android ...

  5. Excel表格文本格式的数字和数字格式如何批量转换

    Excel表格文本格式的数字和数字格式如何批量转换 在使用Excel表格对数据求和时,只能对单元格内常规格式的数据进行计算,而不能对单元格中的文本格式的数据进行计算,特点就是在单元格的左上角有一个绿色 ...

  6. C# 对Excel 单元格格式, 及行高、 列宽、 单元格边框线、 冻结设置

    一.对行高,列宽.单元格边框等的设置 这篇简短的文字对单元格的操作总结的比较全面,特此转载过来. private _Workbook _workBook = null; private Workshe ...

  7. Java将数据按列写入Excel并设置格式(字体、背景色、自动列宽、对齐方式等)

    本文使用jxl.jar工具类库将数据按列写入Excel并设置格式(字体.背景色.自动列宽.对齐方式等). /** * 按列写入Excel并设置格式 * * @param outputUrl * 输出路 ...

  8. 图解-Excel的csv格式特殊字符处理方式尝试笔记(个人拙笔)

    Excel格式如下.(截图来自,WPS Office) CSV是一种文本格式的Excel文档格式.不支持Excel的字体特效(比如加粗,颜色)等等的保存. 每一行数据用 "\n" ...

  9. 03 Uipath调用VBA脚本,处理excel文档格式

    前言: 在平时我们的工作中,经常需要使用Uipath自动的导入大量数据到Excel表格中,但是却发现,数据导入到Excel之后,格式却是很乱,基本不能看,就像下图: ​ 而Uipath对Excel的操 ...

随机推荐

  1. Archlinux在Btrfs分区上的安装(bios篇)

    其实本文所有的内容在Archwiki上都可以找到,并且更新更全面(只是比较零散),我所做的只是对安装流程做一个小小的总结,每一步我都会稍微解释一下,但不会说的特别详细,毕竟这只是一篇安装引导文,而不是 ...

  2. JSWING小工具

    项目中需要一个发送指令到指定服务端,取得设备ID及检测数据的小工具,就利用jswing开发了一个简单小组件,最终效果如下: 代码很简单,具体片段如下: Window.java import java. ...

  3. 转: git常用命令

    # git配置 #---------------------------------------------- #配置用户名和邮箱: $ git config --global user.name & ...

  4. no protocol specified

    基于vncserver安装oracle or oracle RAC时 以root账号运行xhost + 在切换到grid or oracle安装oracle database file or clus ...

  5. 用户向导页面实现左右滑动的ViewPager

    然后在一个博客,以前的博客ImageSwitcher实现用户向导,现在,随着ViewPager实现同样的功能.直接看代码: 布局文件activity_main.xml <RelativeLayo ...

  6. STL-multimap

    转自:http://www.cnblogs.com/xiaoka/archive/2011/08/09/2132342.html multimap提供了可以一种可以有重复键值的STL map类型.其插 ...

  7. 使用 system.io.filesysteminfo 来查找文件。

    如何快速搜索你想找到文件呢.大家知道Windows系统自带了搜索,很方便,下面介绍自己编写的也可以达到同样的效果.注意.有些文件的访问需要更高的权限.这里暂且去掉那些文件目录的搜索.不然会出现erro ...

  8. JavaScript 深入学习及常用工具方法整理 ---- 01.浮点数

    在JavaScript中是不区分整数值和浮点数值的,其中所有的数字均用浮点数值表示.JavaScript采用IEEE 754标准(有兴趣可以浏览网络规范分类下的IEEE 754标准,需要原文件请在留言 ...

  9. string s = HttpContext.Current.Server.MapPath("");

    string s = HttpContext.Current.Server.MapPath(""); 获取当前文件夹路径 而后用相对路径读取图片

  10. Sql Server 2008/2005 数据库还原出现 3154错误

    在Sql Server 2008/2005 数据库还原出现 3154错误 解决方法1:不要在数据库名字上点右键选择还原,而要是在根目录“数据库”三个字上点右键选择还原,然后再选择数据库,问题便可以解决 ...