HOW TO:使用 Visual C# .NET 向 Microsoft Excel 2002 傳輸 XML 數據

概要

Excel 2002 引入了用擴展標記語言 (XML) 格式打開文件的功能。使用用戶界面或代碼可以在 Excel 2002 或 Excel 2003 中直接打開構造良好的 XML 文件。

在 Visual C# .NET 中,您可以利用 Excel 的 XML 功能向工作簿中無縫傳輸數據,從而以您選擇的格式和排列方式呈現數據。本文演示如何完成此任務。

從數據集生成在 Excel 2002 或 Excel 2003 中使用的 XML

本節說明如何創建 DataSet 對象,以及如何使用 WriteXML 方法將該對象包含的數據導出到 XML 文件中。生成的 XML 文件可以直接在 Excel 中打開。爲便於說明,使用 Jet OLEDB 提供程序從 Microsoft Access Northwind 示例數據庫創建了 DataSet 對象。但是,類似的代碼可與您使用 Visual C# .NET 創建的任何 DataSet 對象一起使用。
  1. 啓動 Microsoft Visual Studio .NET。在文件菜單上,單擊新建,然後單擊項目。從 Visual C# 項目類型中選擇 Windows 應用程序。默認情況下創建 Form1。
  2. 視圖菜單上,選擇工具箱以顯示“工具箱”,然後向 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;";
    					
    注意:您可能需要修改連接字符串中 Northwind.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 文件,然後關閉 Form1 以結束該程序。
  9. 啓動 Excel 2002 或 Excel 2003 並打開 C:/Customers.xml 輸出文件。
  10. 在您看到已將 XML 分析成新工作簿中的行和列後,請關閉文件並退出 Excel。

使用樣式表格式化 XML

該步驟介紹如何使用樣式表 (XSL) 來轉換 XML 數據在 Excel 工作簿中的格式和排列方式。
  1. 使用任何 HTML 編輯器或文本編輯器(例如 Notepad.exe),將下面的 XSL 另存爲 C:/Customers.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'");
    					
    此行代碼向 XML 文件寫入了一個處理指令,Excel 使用該指令來查找樣式表 (Customers.xsl)。

  3. 按 F5 鍵生成並運行程序。
  4. 單擊 Button1 以創建 XML 文件,然後關閉 Form1 以結束該程序。
  5. 啓動 Excel 2002 或 Excel 2003 並打開 C:/Customers.xml 輸出文件。
  6. 因爲從 Excel 可以看到 XML 中樣式表的處理指令,所以您在打開文件時會收到一個對話框提示。在導入 XML 對話框中,選擇打開該文件,應用以下樣式表。在列表中,選擇 Customers.xsl 並單擊 確定。注意,XML 數據已格式化,並已經根據樣式表排列各個列。
  7. 關閉該文件並退出 Excel。

使用代碼打開轉換的 XML

此時,您已經使用 Excel 中的用戶界面打開了 XML 文件。本節介紹如何以編程方式使 Excel 自動打開工作簿。下面的示例說明如何通過首先將 DataSet 對象中的 XML 轉換成 HTML 來打開轉換的 XML,而不需要用戶干預。
  1. 添加對 Microsoft Excel 10.0 對象庫或 Microsoft Excel 11.0 對象庫的引用。爲此,請按照下列步驟操作:
    1. 項目菜單上,單擊添加引用
    2. COM 選項卡上,找到 Microsoft Excel 10.0 對象庫或 Microsoft Excel 11.0 對象庫,並單擊選擇
    3. 添加引用對話框中單擊確定以接受您的選擇。如果提示您爲選定的庫生成包裝,請單擊
  2. 將下面的 using 指令添加到 Form1.cs 頂部:
    using Excel = Microsoft.Office.Interop.Excel;
    					
  3. 在 Visual 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 2002 和 Excel 2003 對象模型確實公開了一種 OpenXML 方法(使用該方法,您可以通過編程方式打開應用樣式表的 XML 文件),但前面的示例未調用此方法,原因在於從自動化客戶端使用此方法存在一個已知問題。從 Excel 宏調用 OpenXML 方法時,該方法會以預期方式運行;但是,從自動化客戶端調用此方法時,則會忽略此 StyleSheet 參數。 有關其他信息,請單擊下面的文章編號,以查看 Microsoft 知識庫中相應的文章:

 

參考

有關更多信息,請參閱下面的知識庫文章:

288215 INFO:Microsoft Excel 2002 and XML

302084 HOWTO:從 Visual C# .Net 自動化 Microsoft Excel

301216 HOW TO:Populate a DataSet Object from a Database by Using Visual Basic .NET

306023 HOW TO:Transfer Data to an Excel Workbook by Using Visual C# .NET

這篇文章中的信息適用於:

  • Microsoft Visual C# .NET (2002)
  • Microsoft ADO.NET (included with the .NET Framework) 1.0
  • Microsoft Excel 2002
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章