Microsoft KB Archive/317719

= How To Export Data in a DataGrid on an ASP. NET WebForm to Microsoft Excel =

Article ID: 317719

Article Last Modified on 1/5/2007

-

APPLIES TO


 * Microsoft Excel 2000 Standard Edition
 * Microsoft ASP.NET 1.0
 * Microsoft Excel 2002 Standard Edition

-



This article was previously published under Q317719



IN THIS TASK

 * SUMMARY
 * Techniques
 * Step-by-Step
 * Try It Out!
 * REFERENCES



SUMMARY
Use this step-by-step guide to populate a DataGrid Web server control on an ASP.NET WebForm and then export the contents of the DataGrid to Microsoft Excel.

back to the top

Techniques
This article describes two techniques for exporting the data in the DataGrid:
 * Using the Excel MIME Type (or Content Type)

With server-side code, you can bind the DataGrid to your data and have the data open in Excel on a client computer. To do this, set the ContentType to application/vnd.ms-excel. After the client receives the new stream, the data appears in Excel as if the content was opened as a new page in the Web browser.
 * Using Excel Automation

With client-side code, you can extract the HTML from the DataGrid and then Automate Excel to display the HTML in a new workbook. With Excel Automation, the data always appears outside the browser in an Excel application window. One advantage to Automation is that you can programmatically control Excel if you want to modify the workbook after the data is exported. However, because Excel is not marked as safe for scripting, your clients must apply security settings in the Web browser that allow Automation.

back to the top

Step-by-Step
 Start Visual Studio .NET. On the File menu, point to New, and then click Project. In the Project Types pane, click Visual Basic Projects. Under Templates, click ASP.NET Web Application. Name the application ExcelExport and then click OK.

WebForm1 appears in Design view for you. In Solution Explorer, right-click WebForm1.aspx and then click Rename. Change the name of the file to Bottom.aspx.  On the View menu, click HTML Source to add the following DataGrid between the and tags:    <ItemStyle BorderWidth=&quot;2px&quot; ForeColor=&quot;Black&quot; BorderStyle=&quot;Solid&quot; BorderColor=&quot;Black&quot; BackColor=&quot;#EEEEEE&quot;></ItemStyle> <HeaderStyle Font-Bold=&quot;True&quot; HorizontalAlign=&quot;Center&quot; BorderWidth=&quot;2px&quot; ForeColor=&quot;White&quot; BorderStyle=&quot;Solid&quot; BorderColor=&quot;Black&quot; BackColor=&quot;#000084&quot;></HeaderStyle> <FooterStyle ForeColor=&quot;Black&quot; BackColor=&quot;#CCCCCC&quot;></FooterStyle> <PagerStyle HorizontalAlign=&quot;Center&quot; ForeColor=&quot;Black&quot; BackColor=&quot;#999999&quot; Mode=&quot;NumericPages&quot;></PagerStyle> </asp:datagrid> </li> On the View menu, click Design to return to design view.

The DataGrid appears on the WebForm.</li>  On the View menu, click Code to display the code behind the Web Form. Add the following code to the Page_Load event handler:

Note You must change User ID and password= to the correct values before you run this code. Make sure that the user account has the correct permissions to perform this operation on the database. ' Create a connection and open it. Dim objConn As New System.Data.SqlClient.SqlConnection(&quot;User ID= ;Password= ;Initial Catalog=Northwind;Data Source=SQLServer;&quot;) objConn.Open

Dim strSQL As String Dim objDataset As New DataSet Dim objAdapter As New System.Data.SqlClient.SqlDataAdapter

' Get all the customers from the USA. strSQL = &quot;Select * from customers where country='USA'&quot; objAdapter.SelectCommand = New System.Data.SqlClient.SqlCommand(strSQL, objConn) ' Fill the dataset. objAdapter.Fill(objDataset) ' Create a new view. Dim oView As New DataView(objDataset.Tables(0)) ' Set up the data grid and bind the data. DataGrid1.DataSource = oView DataGrid1.DataBind

' Verify if the page is to be displayed in Excel. If Request.QueryString(&quot;bExcel&quot;) = &quot;1&quot; Then ' Set the content type to Excel. Response.ContentType = &quot;application/vnd.ms-excel&quot; ' Remove the charset from the Content-Type header. Response.Charset = &quot;&quot; ' Turn off the view state. Me.EnableViewState = False

Dim tw As New System.IO.StringWriter Dim hw As New System.Web.UI.HtmlTextWriter(tw)

' Get the HTML for the control. DataGrid1.RenderControl(hw) ' Write the HTML back to the browser. Response.Write(tw.ToString) ' End the response. Response.End End If NOTE: Replace SQLServer in the code with the name of your SQL Server. If you do not have access to a SQL Server that contains the Northwind sample database, modify the connection string to use the Microsoft Access 2002 sample Northwind database:

provider=microsoft.jet.oledb.4.0; data source=C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb

If you select this method, modify the aforementioned code to use the OleDbClient namespace rather than the SqlClient namespace. </li> On the Project menu, click Add HTML Page. Name the page Top.htm and then click Open.

Top.htm appears in Design view.</li>  On the View menu, click HTML Source. Replace the contents of the HTML source window with the following code: <script language=&quot;vbscript&quot;> Sub Button1_onclick

Select Case Select1.selectedIndex

Case 0 ' Use Automation. Dim sHTML sHTML = window.parent.frames(&quot;bottom&quot;).document.forms(0).children(&quot;DataGrid1&quot;).outerhtml Dim oXL, oBook Set oXL = CreateObject(&quot;Excel.Application&quot;) Set oBook = oXL.Workbooks.Add oBook.HTMLProject.HTMLProjectItems(&quot;Sheet1&quot;).Text = sHTML oBook.HTMLProject.RefreshDocument oXL.Visible = true oXL.UserControl = true

Case 1 ' Use MIME Type (In a New Window). window.open(&quot;bottom.aspx?bExcel=1&quot;)

Case 2 ' Use MIME Type (In the Frame). window.parent.frames(&quot;bottom&quot;).navigate &quot;bottom.aspx?bExcel=1&quot; End Select End Sub Export to Excel Using: <SELECT id=&quot;Select1&quot; size=&quot;1&quot; name=&quot;Select1&quot;> <OPTION value=&quot;0&quot; selected>Automation</OPTION> <OPTION value=&quot;1&quot;>MIME Type (In a New Window)</OPTION> <OPTION value=&quot;2&quot;>MIME Type (In the Frame)</OPTION> </SELECT> <INPUT id=&quot;Button1&quot; type=&quot;button&quot; value=&quot;Go!&quot; name=&quot;Button1&quot;> </li> On the Project menu, click Add HTML Page. Name the page Frameset.htm and then click Open.

Frameset.htm opens in Design view.</li>  On the View menu, click HTML Source. Replace the contents of the HTML source window with the following code: <frameset rows=&quot;10%,90%&quot;> <frame noresize=&quot;0&quot; scrolling=&quot;no&quot; name=&quot;top&quot; src=&quot;top.htm&quot;> <frame noresize=&quot;0&quot; scrolling=&quot;yes&quot; name=&quot;bottom&quot; src=&quot;bottom.aspx&quot;> </li> In Solution Explorer, right-click Frameset.htm and then click Set As Start Page.</li> On the Build menu, click Build Solution.</li></ol>

back to the top

Try It Out!

 * 1) On the Debug menu, click Start Without Debugging to run the application.

After the frameset opens in the Web browser, the DataGrid in the bottom frame displays the data from the Northwind database.
 * 1) In the drop-down list, click Automation, and then click Go.

The DataGrid contents are displayed outside the browser in the Microsoft Excel application window.
 * 1) In the drop-down list, click MIME Type (In a New Window), and then click Go.

The DataGrid contents are displayed in Excel hosted in a new Web browser window.

NOTE: If you receive a prompt to open or save the Excel file, click Open.
 * 1) In the drop-down list, click MIME Type (In the Frame) and then click Go.

The DataGrid contents are displayed in the bottom frame of the frameset in Excel hosted in the Web browser.

NOTE: If you receive a prompt to open or save the Excel file, click Open.

back to the top

<div class="references_section">