在Visual C# .Net 中怎样向Microsoft Excel 2002 传输XML数据[译]

英文链接:How To Transfer XML Data to Microsoft Excel 2002 by Using Visual C# .NET 

目录:

 

摘要

通过Excel 2002 Excel 2003从数据集DataSet中生成XML数据

用样式表Stylesheet格式化XML数据

编程打开格式后的XML数据

 

摘要

 

Excel 2002提供了以XML格式打开文件的功能。一个格式合法的XML文件可以通过用户界面和代码直接在Excel 2002Excel 2003中直接打开。

 

通过Visual C#.Net,你可以使用ExcelXML功能将数据传输到工作薄中,并以用户选择的格式和布局显示。本文将演示这些功能的实现。

 

通过Excel 2002 Excel 2003从数据集DataSet中生成XML数据

 

本节描述怎样创建DataSet对象,并通过WriteXml方法将数据传输到XML文件中。可以通过在Excel中直接打开的方式形成XML文件。为了更好的阐述,我们通过Jet OLEDB Provider连接Access中的Northwind样例数据库赖创建DataSet对象。当然,这与通过C#来创建任意DataSet对象的工作方式是相似的。

 

1、  启动Visual Studio .Net。点击“文件”菜单,选择“新建”中的“项目”选项。从项目类型中选择“Windows应用程序”,默认将创建Form1对象。

2、  在“查看”菜单,选择“工具箱”以显示工具箱,并添加一个button到窗体Form1中。

3、  双击Button1,显示代码窗口。

4、  添加下面的Using语句到Form1.cs的顶部:

using System.Data.OleDb;

using System.Xml;

5、  Form1类中添加如下的私有成员变量:

private string strConn ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="

+ " C:\\Program Files\\Microsoft Office\\Office10\\Samples\\"

+ "Northwind.mdb;";

注意:你应该修改在connectionNorthwind.mdb的路径,以匹配你的安装。

6、  button1_Click事件中添加如下的代码:

 //Connect to the data source.

         OleDbConnection objConn = new OleDbConnection (strConn);

         try

         {

            objConn.Open();       

 

            //Fill a dataset with records from the Customers table.

            OleDbCommand objCmd = new OleDbCommand(

               "Select CustomerID, CompanyName, ContactName, "

               + "Country, Phone from Customers", objConn);

            OleDbDataAdapter objAdapter = new OleDbDataAdapter();

            objAdapter.SelectCommand = objCmd;

            DataSet objDataset = new DataSet();

            objAdapter.Fill(objDataset);

 

 

            //Create the FileStream to write with.

            System.IO.FileStream fs = new System.IO.FileStream(

               "C:\\Customers.xml", System.IO.FileMode.Create);

 

            //Create an XmlTextWriter for the FileStream.

            System.Xml.XmlTextWriter xtw = 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("xml", "version='1.0'");

            //xtw.WriteProcessingInstruction("xml-stylesheet",

              // "type='text/xsl' href='customers.xsl'");

 

            //Write the XML from the dataset to the file.

            objDataset.WriteXml(xtw);

            xtw.Close();

 

            //Close the database connection.

            objConn.Close();

         }

         catch (System.Exception ex)

         {

            MessageBox.Show(ex.Message);

         }

7、  F5编译并运行程序。

8、  单击Button1以创建XML文件,关闭窗体结束程序。

9、  启动Excel 2002Excel 2003,打开上一步创建的Customers.xml文件。

10、你可以看到XML文件已经被解析为新工作薄中的行和列,关闭文件退出Excel

 

用样式表Stylesheet格式化XML数据

 

接下来将演示怎样通过XSL(样式表stylesheet)格式化XML数据使其符合Excel工作薄。

1、  HTML编辑器或文本编辑器(如记事本),编辑如下的XSL并保存到C:\Customer.xsl中:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="/">

    <HTML>

      <HEAD>

        <STYLE>  

          .HDR { background-color:bisque;font-weight:bold }

        </STYLE>

      </HEAD>

      <BODY>

        <TABLE>

          <COLGROUP WIDTH="100" ALIGN="CENTER"></COLGROUP>

          <COLGROUP WIDTH="200" ALIGN="LEFT"></COLGROUP>

          <COLGROUP WIDTH="200" ALIGN="LEFT"></COLGROUP>

          <COLGROUP WIDTH="100" ALIGN="LEFT"></COLGROUP>

          <COLGROUP WIDTH="100" ALIGN="LEFT"></COLGROUP>

          <TD CLASS="HDR">Customer ID</TD>

          <TD CLASS="HDR">Company</TD>

          <TD CLASS="HDR">Contact</TD>

          <TD CLASS="HDR">Country</TD>

          <TD CLASS="HDR">Phone</TD>

          <xsl:for-each select="NewDataSet/Table">

            <TR>

              <TD><xsl:value-of select="CustomerID"/></TD>

              <TD><xsl:value-of select="CompanyName"/></TD>

              <TD><xsl:value-of select="ContactName"/></TD>

              <TD><xsl:value-of select="Country"/></TD>

              <TD><xsl:value-of select="Phone"/></TD>

            </TR>

          </xsl:for-each>

        </TABLE>

      </BODY>

    </HTML>

  </xsl:template>

</xsl:stylesheet>

2、  button1_Click事件中将下面一行代码的注释取消:

xtw.WriteProcessingInstruction("xml-stylesheet",

"type='text/xsl' href='customers.xsl'");

这一行代码为Excel提供了处理向导(a processing instuction),将XML文件定位到样式表文件Customer.xsl上。

3、  F5编译并运行程序。

4、  单击Button1创建XML文件,关闭Form1结束程序。

5、  启动Excel 2002Excel 2003,打开上一步创建的Customers.xml文件。

6、  因为Excel检测到XML数据中有对样式表的处理向导,所以当你打开文件时会弹出一个对话框。在“(导入XML)Import XML”对话框中,选择“打开下列样式表文件(Open the file with the following stylesheet applied”。在列表中,选择Customer.xsl并单击确定“OK”。注意该XML数据已被格式化,因此列将根据样式表规定的格式排列。

7、  关闭文件退出Excel

 

编程打开格式后的XML数据

 

在前面,我们是在Excel中通过用户界面直接打开的XML文件。本节将演示怎样通过程序激活Excel以打开工作薄。下面的示例说明怎样打开格式后的XML数据,而不需要通过用户操作将DataSet对象中的XML数据转换为HTML

 

1、  添加引用:Microsoft Excel 10.0 Object LibraryMicrosoft Excel 11.0 Object Library。步骤如下:

a、  在“项目”菜单中,单击“添加引用”。

b、  在“COM”标签中,找到Microsoft Excel 10.0 Object LibraryMicrosoft Excel 11.0 Object Library,单击“选择”。

2、  Form1.cs中添加using

using Excel = Microsoft.Office.Interop.Excel;

3、  Visula C#.Net项目中,添加另一个按钮到Form1中。

4、  双击Button2。在代码窗口中的Button2_Click事件中添加如下代码:

//Connect to the data source.

OleDbConnection objConn = new OleDbConnection (strConn);

objConn.Open();       

 

//Fill a dataset with records from the Customers table.

OleDbCommand objCmd = new OleDbCommand(

"Select CustomerID, CompanyName, ContactName, "

+ "Country, Phone from Customers", objConn);

OleDbDataAdapter objAdapter = new OleDbDataAdapter();

objAdapter.SelectCommand = objCmd;

DataSet objDataset = new DataSet();

objAdapter.Fill(objDataset);

 

//Create the FileStream to write with.

System.IO.FileStream fs = new System.IO.FileStream(

"C:\\Customers.htm", System.IO.FileMode.Create);

 

//Create an XmlTextWriter for the FileStream.

System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(

fs, System.Text.Encoding.Unicode);

 

//Transform the XML using the stylesheet.

XmlDataDocument xmlDoc = new XmlDataDocument(objDataset);

System.Xml.Xsl.XslTransform xslTran = new System.Xml.Xsl.XslTransform();

xslTran.Load("C:\\Customers.xsl");

xslTran.Transform(xmlDoc, null, xtw);

 

//Open the HTML file in Excel.

Excel.Application oExcel = new Excel.Application();

oExcel.Visible=true;

oExcel.UserControl=true;

Excel.Workbooks oBooks = oExcel.Workbooks;

object oOpt = System.Reflection.Missing.Value; //for optional arguments

oBooks.Open("c:\\customers.htm", oOpt, oOpt, oOpt,

oOpt, oOpt, oOpt, oOpt, oOpt, oOpt, oOpt, oOpt,

oOpt, oOpt, oOpt);

5、  F5编译并运行程序。

6、  单击Button2打开在Excel中已格式化的XML数据。

 

注意:Excel 2002Excel 2003对象模式暴露了OpenXML方法,使用户可以通过程序的方式打开应用了样式表的XML文件。上面的例子没有使用该方法是因为在Automation client模式下调用该方法存在问题。当我们从Excel宏(Excel macro)中调用OpenXML方法时,运行是正确的,然而如果以Automation client方式调用,StyleSheet参数会被忽略。如果要了解更多信息,可以参考微软知识库中的这篇文章:

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

相关文章:

如何使用 ASP.NET、ADO.NET 和 Visual C# .NET 查询和显示 Excel 数据

posted @ 2004-08-01 13:56  张逸  阅读(2543)  评论(0编辑  收藏  举报