Microsoft KB Archive/311194

= HOW TO: Use ASP.NET to Query and Display Database Data in Excel by Using Visual C# .NET =

Article ID: 311194

Article Last Modified on 1/19/2004

-

APPLIES TO


 * Microsoft ASP.NET 1.1
 * Microsoft ASP.NET 1.0
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q311194





For a Microsoft Visual Basic .NET version of this article, see 308247.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Data.SqlClient
 * System.IO
 * System.Text

IN THIS TASK
SUMMARY
 * Build the Sample Code
 * Troubleshooting



SUMMARY
This step-by-step article describes how to build a tab-delimited text file dynamically from a database. You can then open the file in Microsoft Excel. The sample code in this article demonstrates how to connect to a Microsoft SQL Server database, return a set of data from the Pubs database, and then create a tab-delimited text file with the data.

back to the top

Build the Sample Code
This example creates a sample ASP.NET Visual C# .NET page named ExcelCS.aspx. This page connects to the SQL Server Pubs database and uses the FileStream object to return the information to a tab-delimited text file. The ASP.NET page then displays a link to the .xls file that you created to demonstrate the output of the code.  Start Microsoft Visual Studio .NET. On the File menu, point to New, and then click Project. In the New Project dialog box, under Project Types, click Visual C# Projects. Under Templates, click ASP.NET Web Application. In the Location box, type the server name and the project name in the following format:

http:// /

In this example, name the project ExcelCSTest. If you are using the local server, you can leave the server name as http://localhost.

 Drag a HyperLink control from the toolbox to the WebForm1.aspx file. Right-click WebForm1.aspx, and then click View Code to display the code-behind page source.</li>  Add the following statements to the top of the code-behind page: using System.Data.SqlClient; using System.IO; using System.Text; </li>  In the code-behind page of WebForm1.aspx, add the following code to the Page_Load event: //You use these variables throughout the application. string fileExcel, filePath, fileName, strLine, sql; FileStream objFileStream; StreamWriter objStreamWriter; Random nRandom = new Random(DateTime.Now.Millisecond); SqlConnection cnn = new SqlConnection(&quot;server=(local);database=pubs;Integrated Security=SSPI&quot;);

//Create a random file name. fileExcel = &quot;t&quot; + nRandom.Next.ToString + &quot;.xls&quot;; //Set a virtual folder to save the file. //Make sure to change the application name to match your folder. filePath = Server.MapPath(&quot;\\ExcelCSTest&quot;); fileName = filePath + &quot;\\&quot; + fileExcel;

//Use FileSystem objects to create the .xls file. objFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); objStreamWriter = new StreamWriter(objFileStream);

//Use a DataReader object to connect to the Pubs database. cnn.Open; sql = &quot;select au_id,au_lName,au_fname,phone,address,city,state,zip,contract from authors&quot;; SqlCommand cmd = new SqlCommand(sql, cnn); SqlDataReader dr; dr = cmd.ExecuteReader;

//Initialize the string that is used to build the file. strLine = &quot;&quot;; //Enumerate the field names and the records that are used to build //the file. for (int i = 0; i <= dr.FieldCount-1; i++) {     strLine = strLine + dr.GetName(i).ToString + Convert.ToChar(9); }

//Write the field name information to the file. objStreamWriter.WriteLine(strLine);

//Reinitialize the string for data. strLine = &quot;&quot;;

//Enumerate the database that is used to populate the file. while (dr.Read) {     for (int i = 0; i <= dr.FieldCount-1; i++) {        strLine = strLine + dr.GetValue(i).ToString + Convert.ToChar(9); }                         objStreamWriter.WriteLine(strLine); strLine=&quot;&quot;; }

//Clean up. dr.Close; cnn.Close; objStreamWriter.Close; objFileStream.Close;

//Include a link to the Excel file. HyperLink1.Text=&quot;Open Excel&quot;; HyperLink1.NavigateUrl=fileExcel; </li> Modify the connection string (SqlConnection) as necessary for your environment.</li> On the File menu, click Save All to save the project files.</li> On the Build menu in the Visual Studio .NET Integrated Development Environment (IDE), click Build Solution to build the project.</li> In Visual Studio .NET Integrated Development Environment Solution Explorer, right-click WebForm1.aspx, and then click View in Browser to run the code.</li></ol>

back to the top

Troubleshooting
<ul> You must change the connection string in the code sample to match your environment.</li> You may have to increase permissions for the aspnet_wp process (in Microsoft Windows 2000 and in Microsoft Windows XP) or the w3wp process (in Microsoft Windows Server 2003) to allow the file to be written. For additional information, click the following article number to view the article in the Microsoft Knowledge Base:

317012 INFO: Process and Request Identity in ASP.NET

</li></ul>

back to the top

Keywords: kbhowtomaster kbio kbdatabase KB311194

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.