Export ASP. NET DataGrid to excel

Source: Internet
Author: User

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: Mike Dolan Date: August 13,200 3 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, degree 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 simpler and more adaptable way to export the DataGrid itself to excel. I kept the concept to a component class so that it cocould easily be used throughout an application.

I created the following component. I used. 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 wocould 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 wowould 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 wocould 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 have CT 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"> <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. essential tially 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 return
'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. net, once you
'Build your solution after creating the component, intelliisense 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.