分享
 
 
 

Export ASP.NET DataGrid To Excel

王朝asp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

Exporting DataGrids to Excel...

Ken Walker's article on exporting DataSets to Excel has proved very popular. This article by Mike Dolan presents a different technique for getting a DataGrid rather than the DataSet into Excel. We believe you will find it very useful.

By: John KilgoMike Dolan

Date: August 13, 2003
Download the code.
Printer Friendly Version

I have a Datagrid with a Dataset as its datasource that I want to export to Excel. Using Ken Walker's awesome tutorial ( http://www.dotnetjohn.com/articles/articleid36.aspx) on how to pass Datasets to Excel via a component, I was able to easily send a dataset to excel from anywhere in my application. However, a few things didn't end up working out for my application. First, I needed to clean up the formatting. Second, many of my datagrids had columns that were calculated from data in the datasets. Third, the header row in Excel always contained the database column names which were sometimes unintelligible to an ordinary user. My final problem was that often the Datasets contained data necessary for the datagrid generation, but that we didn't want the end user to see.

To remedy all these issues I came up with the a simpler and more adaptable way to export the datagrid itself to Excel. I kept the concept to a component class so that it could easily be used throughout an application.

I created the following component. I used VS.Net and left out the "Component Designer Generated Code Region". What you will find is that the class has one method that takes in two arguments: A datagrid and a response. It works by simply writing a datagrid to the htmltextwriter just like Ken Walker's artice wrote the dataset table to the stringwriter.

I also included sections on how to change formatting. In the application we built, we wanted our Excel exports to have a standardized look. The middle-end section shows different types of formatting changes that can be made at the class level.

cmpDataGridToExcel.vb

Public Class cmpDataGridToExcel

Inherits System.ComponentModel.Component

Public Shared Sub DataGridToExcel(ByVal dgExport As DataGrid, ByVal response As HttpResponse)

'clean up the response.object

response.Clear()

response.Charset = ""

'set the response mime type for excel

response.ContentType = "application/vnd.ms-excel"

'create a string writer

Dim stringWrite As New System.IO.StringWriter()

'create an htmltextwriter which uses the stringwriter

Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)

'instantiate a datagrid

Dim dg As New DataGrid()

' just set the input datagrid = to the new dg grid

dg = dgExport

' I want to make sure there are no annoying gridlines

dg.GridLines = GridLines.None

' Make the header text bold

dg.HeaderStyle.Font.Bold = True

' If needed, here's how to change colors/formatting at the component level

'dg.HeaderStyle.ForeColor = System.Drawing.Color.Black

'dg.ItemStyle.ForeColor = System.Drawing.Color.Black

'bind the modified datagrid

dg.DataBind()

'tell the datagrid to render itself to our htmltextwriter

dg.RenderControl(htmlWrite)

'output the html

response.Write(stringWrite.ToString)

response.End()

End Sub

End Class

After the component above was created/compiled, we then moved to the actual page that generated the Datagrid we would pass to the component. One of our datagrids looked like the following:

As you can see we have totals, discounts, and Boolean approval checkboxes. Most of these fields are presented generated from data using functions. Even the store number is output of a function. The Dataset export would have looked nothing like what you see above.

The following in based on a dataset taken from our SQL server. Just like in Ken's article, it doesn't matter how you generate the dataset or datagrid. Just create a datagrid and format it the way you want. Our datagrid above was generated with the following:

For security and copyright reasons, I will only include a small portion of our aspx page. The datagrid we created contains mostly template columns generated in this fashion:

InvoiceApproval.aspx Code Snippet

<asp:BoundColumn DataField="strInvoiceNo" ReadOnly="True" HeaderText="Invoice#"></asp:BoundColumn>

<asp:TemplateColumn HeaderText="Store #">

<ItemTemplate>

<%# GetStore(DataBinder.Eval(Container.DataItem, "intCustomerID")) %>

</ItemTemplate>

</asp:TemplateColumn>

<asp:TemplateColumn HeaderText="LA">

<ItemTemplate>

<%# GetLabor(DataBinder.Eval(Container.DataItem, "dblLabor"), DataBinder.Eval(Container.DataItem, "dblService")) %>

</ItemTemplate>

</asp:TemplateColumn>

GetStore and GetLabor are simply functions we called passing the database data for the customer id and labor/service charges respectively. You can create your datagrid however you want, this simply shows why a dataset export with intCustomerID and not a Store # as we needed would not work.

A Northwind Database Example

Every tutorial needs a full example from the Northwind or Pubs database. The following is the Example.aspx file that displays the datagrid. We are still using the same component as you see above for the export.

The page contains one datagrid dgToExport and then a button to export. The datagrid is formatted and we expect the formatting and the headers to show exactly like this when we export to Excel.

DataGridExport.aspx

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="DataGridExport.aspx.vb" Inherits="ExportExample.DataGridExport"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<title>DataGridExport</title>

<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">

<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">

<meta name="vs_defaultClientScript" content="JavaScript">

<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

</HEAD>

<body>

<div align="center">

<form id="Form1" method="post" runat="server">

<P>

<asp:DataGrid id="dgToExport" runat="server" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3" GridLines="Vertical" AutoGenerateColumns="False">

<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#008A8C"></SelectedItemStyle>

<AlternatingItemStyle BackColor="Gainsboro"></AlternatingItemStyle>

<ItemStyle ForeColor="Black" BackColor="#EEEEEE"></ItemStyle>

<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#000084"></HeaderStyle>

<FooterStyle ForeColor="Black" BackColor="#CCCCCC"></FooterStyle>

<Columns>

<asp:BoundColumn DataField="EmployeeID" ReadOnly="True" HeaderText="ID"></asp:BoundColumn>

<asp:TemplateColumn HeaderText="Name">

<ItemTemplate>

<%# ReturnName(DataBinder.Eval(Container.DataItem, "LastName"), DataBinder.Eval(Container.DataItem, "FirstName")) %>

</ItemTemplate>

</asp:TemplateColumn>

<asp:BoundColumn DataField="Title" ReadOnly="True" HeaderText="Title"></asp:BoundColumn>

</Columns>

<PagerStyle HorizontalAlign="Center" ForeColor="Black" BackColor="#999999" Mode="NumericPages"></PagerStyle>

</asp:DataGrid>

</P>

<P>

<asp:Button id="btnExport" runat="server" Text="Export to Excel"></asp:Button></P>

</form>

</div>

</body>

</HTML>

And now to the codebehind where everything happens. Essentially I have the Northwind database table Employees coming in via the SqlDataAdapter1 to fill DataSet1. Then the datagrid is bound to the dataset. The btnExport handles the export to excel when a user clicks it. You will also see the simple function to combine names. Once the grid is exported, the names will be together in one cell. I left out the Designer code.

DataGridExport.aspx.vb

Public Class DataGridExport

Inherits System.Web.UI.Page

Protected WithEvents SqlSelectCommand1 As System.Data.SqlClient.SqlCommand

Protected WithEvents SqlInsertCommand1 As System.Data.SqlClient.SqlCommand

Protected WithEvents SqlUpdateCommand1 As System.Data.SqlClient.SqlCommand

Protected WithEvents SqlDeleteCommand1 As System.Data.SqlClient.SqlCommand

Protected WithEvents SqlConnection1 As System.Data.SqlClient.SqlConnection

Protected WithEvents SqlDataAdapter1 As System.Data.SqlClient.SqlDataAdapter

Protected WithEvents dgToExport As System.Web.UI.WebControls.DataGrid

Protected WithEvents btnExport As System.Web.UI.WebControls.Button

Protected WithEvents Form1 As System.Web.UI.HtmlControls.HtmlForm

Protected WithEvents DataSet1 As System.Data.DataSet

' Web Form Designer Generated Code left out

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here

BindGrid()

End Sub

Sub BindGrid()

' Fill our dataset

SqlDataAdapter1.Fill(DataSet1)

' Assign the dataset to our Datagrid called dgToExport

dgToExport.DataSource = DataSet1

' Finally bind the datagrid

dgToExport.DataBind()

End Sub

Function ReturnName(ByVal strLastName, ByVal strFirstName)

' This is the function I'm calling in the aspx page to show the difference

' between exporting a dataset versus exporting a datagrid. This function is

' simply going to combine the first and last names and and return the

' full name to the datagrid template column for "Name".

Dim strReturn As String

strReturn = strFirstName & " " & strLastName

Return strReturn

End Function

Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click

' One line handles all of the export. We're simply calling the component (cmpDataGridToExcel),

' then we're using it's only method (DataGridToExcel), and we're passing our DataGrid (dgToExport) and the value reponse. Note: If you're using VS.Net, once you

' build your solution after creating the component, Intellisense will now include your

' component. Just remember you have to build it first.

'

' You could also modify your datagrid here before exporting it. For instance in my

' invoice example we had a checkbox in our datagrid. If you have one of those the export

' will generate an error so we simply removed the column first like this before exporting:

' dgToExport.Columns.Remove(dgToExport.Columns.Item(11))

cmpDataGridToExcel.DataGridToExcel(dgToExport, Response)

End Sub

End Class

And that's all there is to it. Just create the component, compile it, and then once you have your datagrid setup one line exports it nice and cleanly to Excel at the click of a button. I hope this works out and possibly improves upon Ken Walker's great article that helped me understand how this whole string writing thing worked.

You may run the program here.

You may download the code here.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有