In order to export data from a GridView control, ensure that the AllowSorting and
AllowPaging properties are turned off. I will add two buttons in the user interface
that correspond to the export format types, that is, I will show you how to export
data to MS Excel and MS Word Word. Refer to the following screenshot which illustrates
the application in execution with two buttons that can be used to export the data in
the GridView control to MS Excel and MS Word respectively.
Note the two buttons with their respective captions beneath the GridView control
populated with data.
Displaying Views of Data (Part I)
[ 170 ]
Now once you click on the Export to Excel button, a window pops up, as shown in
the following screenshot:
Once you click on the Open button, the data from the GridView control is exported
to Excel and displayed in an Excel Worksheet, as shown in the following screenshot:
Chapter 6
[ 171 ]
Let us now understand how we achieved this. In the click event of these buttons,
you need to write the necessary code to export the data. Following is the code for the
Click events of these buttons:
protected void btnExportGridViewToExcel_Click(object sender,
EventArgs e)
{
ExportToExcel();
}
protected void btnExportGridViewToWord_Click(
object sender, EventArgs e)
{
ExportToWord();
}
Note that we have invoked the ExportToExcel() and the ExportToWord() methods
respectively in the Click events of these buttons.
Pages:
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172