文章編號: 307029 - 上次校閱: 2006年12月11日 - 版次: 7.5

如何將 XML 資料傳送至 Microsoft Excel 2002 或 Microsoft Excel 2003 中,藉由使用 Visual C#

系統提示本文適用於您使用的作業系統之外的作業系統。與您不相關的文章內容已停用。
本文章的有 Microsoft Visual Basic.NET] 版本請參閱 307021? (http://support.microsoft.com/kb/307021/ )

在此頁中

全部展開 | 全部摺疊

結論

Excel 2002 會介紹以 「 可延伸標記語言 」 (XML) 格式開啟檔案的功能。是語式正確的 XML 檔案可以直接在 Excel 2002 或 Excel 2003 中開啟使用使用者介面] 或 [程式碼。

與 Microsoft Visual C# 2005年或 Microsoft Visual C#.NET,您可以帶著不著痕跡地傳輸資料到活頁簿,呈現格式化的資料 Excel 的 XML 功能的優點和您所選擇的一種排列方式。本文將告訴您,如何完成這項工作。

從在 Excel 2002 或 Excel 2003 中使用資料集產生 XML

本節說明如何建立 資料集 物件,以及它包含了將資料匯出至 XML 檔案使用 WriteXML 方法。可以直接在 Excel 中開啟 XML 檔案,就會產生。供說明之用 DataSet 物件是使用 Jet OLEDB 提供者來建立從 Microsoft Access 的北風貿易範例資料庫中。不過,類似的程式碼可搭配使用 Visual C# 2005年或 Visual C#.NET 建立的任何 資料集 物件。
  1. 啟動 Microsoft Visual Studio 2005 或 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);
             } 
    					
    附註 您必須變更程式碼,在 Visual Studio 2005 中的。預設情況下,Visual C# 將一表單加入專案建立 Windows Form 專案時。表單名為 Form1。代表表單的兩個檔案被命名 Form1.cs 和 Form1.designer.cs。Form1.cs 中撰寫程式碼。Form1.designer.cs 檔案是其中 Windows Form 設計工具寫入程式碼會實作所有動作您執行藉由拖放控制項從 [工具箱]。

    如需有關 Windows Form 設計工具在 Visual C# 2005年中的詳細資訊,請造訪下列 Microsoft 開發人員網路 MSDN 網站:
    http://msdn2.microsoft.com/en-us/library/ms173077.aspx (http://msdn2.microsoft.com/en-us/library/ms173077.aspx)
  7. 按下 F5 以建置並執行程式。
  8. 按一下 [Button1] 來建立 XML] 檔案,然後關閉 [Form1] 以結束程式。
  9. 啟動 Excel 2002 或 Excel 2003 並開啟 C:\Customers.xml 輸出檔。
  10. 您有觀察到如何將 XML 已被剖析成新的活頁簿中的列和欄之後關閉檔案,然後結束 Excel。

格式化 XML 使用樣式表

此步驟會顯示如何使用樣式表 (XSL) 來轉換 XML 資料被格式化和排列在 Excel 活頁簿中。
  1. Using any HTML editor or a text editor (such as Notepad.exe), save the following XSL as 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 以程式設計的方式開啟活頁簿。下列範例會說明如何開啟 [已轉換的 XML 沒有使用者介入的情況下],請依第一個轉換成 HTML 格式 DataSet 物件中的 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# 2005年或 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. 按一下 [在 Excel 中開啟已轉換的 XML Button2
附註雖然 Excel 2002 和 Excel 2003 物件模型不會公開的 OpenXML 方法時,可讓您以程式設計的方式開啟 XML 檔案時套用的樣式表具有,先前的範例並不呼叫這個方法已知問題與使用自動化用戶端從這個方法。OpenXML 方法的運作方式如預期般地從 Excel 巨集呼叫時 ; 不過,當呼叫這個方法從自動化用戶端,樣式表 參數已忽略。 如需詳細資訊按一下面的文件編號,檢視 「 Microsoft 知識庫 」 中的發行項:
307230? (http://support.microsoft.com/kb/307230/EN-US/ ) 注意: 樣式表自動化 Excel 2002 時,忽略之 OpenXML 方法參數

?考

如需詳細資訊請參閱下列知識庫文件]:
288215? (http://support.microsoft.com/kb/288215/EN-US/ ) 資訊: Microsoft Excel 2002 和 XML
302084? (http://support.microsoft.com/kb/302084/EN-US/ ) 如何自動化 Microsoft Excel 從 Visual C#.NET
301216? (http://support.microsoft.com/kb/301216/EN-US/ ) 如何使用 Visual Basic.NET 填入 DataSet 物件從一個資料庫
306023? (http://support.microsoft.com/kb/306023/EN-US/ ) 如何使用 Visual C#.NET 傳輸資料到 Excel 活頁簿

這篇文章中的資訊適用於:
  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft ADO.NET 1.0
  • Microsoft Excel 2002 Standard Edition
  • Microsoft Office Excel 2003
關鍵字:?
kbmt kbhowtomaster KB307029 KbMtzh
機器翻譯機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:307029? (http://support.microsoft.com/kb/307029/en-us/ )
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。