Microsoft KB Archive/307021

= HOW TO: Transfer XML Data to Microsoft Excel 2002 by Using Visual Basic .NET =

Article ID: 307021

Article Last Modified on 12/12/2003

-

APPLIES TO


 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft .NET Framework 1.1 Service Pack 1
 * Microsoft Excel 2002 Standard Edition

-



This article was previously published under Q307021



For a Microsoft Visual C# .NET version of this article, see 307029.

IN THIS TASK

 * SUMMARY
 * Generate XML from a DataSet For Use In Excel 2002 or Excel 2003
 * Format the XML Using a Stylesheet
 * Use Code to Open the Transformed XML
 * REFERENCES



SUMMARY
Excel 2002 introduces functionality for opening files in the Extensible Markup Language (XML) format. An XML file that is well-formed can be opened directly in Excel 2002 or Excel 2003 by using either the user interface or code.

With Visual Basic .NET, you can take advantage of Excel's XML functionality to seamlessly transfer data to a workbook to present the data with formatting and an arrangement of your choice. This article demonstrates how to accomplish this task.

back to the top

Generate XML from a DataSet For Use In Excel 2002 or Excel 2003
This section illustrates how to create a DataSet object and export the data that it contains to an XML file by using the WriteXML method. The XML file that is generated can be opened directly in Excel. For illustration purposes, the DataSet object is created from the Microsoft Access Northwind sample database by using the Jet OLEDB Provider. However, similar code works with any DataSet object that you create with Visual Basic .NET.  Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project. Select Windows Application from the Visual Basic Projects types. Form1 is created by default. On the View menu, select Toolbox to display the Toolbox and add a button to Form1. Double-click Button1. The code window for the Form appears.  Add the following private member variable to the Form1 class: Private strConn As String = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=&quot; & _ &quot;C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb;&quot; NOTE: You may need to modify the path to Northwind.mdb in the connection string to match your installation.

  Add the following code to the Button1_Click handler: 'Connect to the data source. Dim objConn As New System.Data.OleDb.OleDbConnection(strConn)

Try objConn.Open

'Fill a dataset with records from the Customers table. Dim strSQL As String Dim objDataset As New DataSet Dim objAdapter As New System.Data.OleDb.OleDbDataAdapter strSQL = &quot;Select CustomerID, CompanyName, ContactName, &quot; & _ &quot;Country, Phone from Customers&quot; objAdapter.SelectCommand = New System.Data.OleDb.OleDbCommand( _           strSQL, objConn) objAdapter.Fill(objDataset)

' Create the FileStream to write with. Dim strFilename As String strFilename = &quot;C:\Customers.xml&quot; Dim fs As New System.IO.FileStream(strFilename, _           System.IO.FileMode.Create)

'Create an XmlTextWriter for the FileStream. Dim xtw As New System.Xml.XmlTextWriter(fs, _           System.Text.Encoding.Unicode)

'Add processing instructions to the beginning of the XML file, one 'of which indicates a style sheet. xtw.WriteProcessingInstruction(&quot;xml&quot;, &quot;version='1.0'&quot;) 'xtw.WriteProcessingInstruction( _       '    &quot;xml-stylesheet&quot;, &quot;type='text/xsl' href='customers.xsl'&quot;)

'Write the XML from the dataset to the file. objDataset.WriteXml(xtw) xtw.Close

MsgBox(&quot;Customer data has been exported to C:\Customers.xml.&quot;)

Catch ex As Exception MsgBox(ex.Message) End Try  Press F5 to build and run the program. Click Button1 to create the XML file, then close Form1 to end the program.</li> Start Excel 2002 or Excel 2003 and open the C:\Customers.xml output file.</li> After you have observed how the XML has been parsed into rows and columns in the new workbook, close the file and quit Excel.</li></ol>

back to the top

Format the XML Using a Stylesheet
This step shows you how to use a stylesheet (XSL) to transform how XML data is formatted and arranged in an Excel workbook. <ol>  Using any HTML editor or a text editor (such as Notepad.exe), save the following XSL as C:\Customers.xsl: <xsl:stylesheet xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; version=&quot;1.0&quot;> <xsl:template match=&quot;/&quot;> <HTML> <HEAD> <STYLE> .HDR { background-color:bisque;font-weight:bold } </STYLE> </HEAD> <BODY> </BODY> </HTML> </xsl:template> </xsl:stylesheet> </li>  Uncomment the following line of code in the Button1_Click handler: xtw.WriteProcessingInstruction( _           &quot;xml-stylesheet&quot;, &quot;type='text/xsl' href='customers.xsl'&quot;) This line of code writes a processing instruction to the XML file that Excel uses to locate the stylesheet (Customers.xsl).

</li> Press F5 to build and run the program.</li> Click Button1 to create the XML file, then close Form1 to end the program.</li> Start Excel 2002 or Excel 2003 and open the C:\Customers.xml output file.</li> Because Excel sees the processing instruction for the stylesheet in the XML, you receive a dialog box prompt when you open the file. In the Import XML dialog box, select Open the file with the following stylesheet applied. In the list, select Customers.xsl and click OK. Note that the XML data is formatted and that the columns have been arranged according to the stylesheet.</li> Close the file and quit Excel.</li></ol>

back to the top

Use Code to Open the Transformed XML
Up to this point, you have opened the XML file by using the user interface in Excel. This section demonstrates how to automate Excel to open the workbook programmatically. The following sample illustrates how to open the transformed XML without user intervention by first transforming the XML in the DataSet object to HTML. <ol> In the Visual Basic .NET project, add another button to Form1.</li>  Double-click Button2. When the code window for the form appears, add the following code to the Button2_Click handler: 'Connect to the data source. Dim objConn As New System.Data.OleDb.OleDbConnection(strConn) objConn.Open

'Fill a dataset with records from the Customers table. Dim strSQL As String Dim objDataset As New DataSet Dim objAdapter As New System.Data.OleDb.OleDbDataAdapter strSQL = &quot;Select CustomerID, CompanyName, ContactName, &quot; & _ &quot;Country, Phone from Customers&quot; objAdapter.SelectCommand = New System.Data.OleDb.OleDbCommand( _           strSQL, objConn) objAdapter.Fill(objDataset)

' Create the FileStream to write with. Dim strFilename As String strFilename = &quot;C:\Customers.htm&quot; Dim fs As New System.IO.FileStream(strFilename, _           System.IO.FileMode.Create)

'Create an XmlTextWriter for the FileStream. Dim xtw As New System.Xml.XmlTextWriter(fs, _           System.Text.Encoding.Unicode)

'Transform the XML using the stylesheet. Dim xmlDoc As System.Xml.XmlDataDocument = _ New System.Xml.XmlDataDocument(objDataset) Dim xslTran As System.Xml.xsl.XslTransform = _ New System.Xml.Xsl.XslTransform xslTran.Load(&quot;c:\customers.xsl&quot;) xslTran.Transform(xmlDoc, Nothing, xtw)

'Write the transformed XML to the file. objDataset.WriteXml(xtw) xtw.Close

'Start Excel and open the resulting file. Dim oExcel As Object oExcel = CreateObject(&quot;Excel.Application&quot;) oExcel.Workbooks.Open(&quot;C:\Customers.htm&quot;)

'Make Excel visible and give the user control of the application. oExcel.Visible = True oExcel.UserControl = True </li> Press F5 to build and run the program.</li> Click Button2 to open the transformed XML in Microsoft Excel.</li></ol>

NOTE: While the Excel 2002 and Excel 2003 Object Model does expose an OpenXML method that enables you to programmatically open an XML file with stylesheets applied, the previous sample does not call this method due to a known problem with using this method from an Automation client. The OpenXML method works as expected when it is called from an Excel macro; however, when this method called from an Automation client, the StyleSheet parameter is ignored. For additional information, click the article number below to view the article in the Microsoft Knowledge Base:

307230 BUG: StyleSheets Parameter of the OpenXML Method Ignored When Automating Excel 2002

back to the top

<div class="references_section">