使用 VSTO 增益集將自訂 XML 組件新增至文件

您可以將 XML 資料儲存在下列類型的文件中,方法是在 VSTO 增益集中建立自訂 XML 組件:

將自訂 XML 組件加入至 Excel 活頁簿

  1. 將新的 CustomXMLPart 物件加入至活頁簿中的 CustomXMLParts 集合。 CustomXMLPart 包含您要儲存在活頁簿中的 XML 字串。

    下列程式碼範例會將自訂 XML 組件加入至指定的活頁簿。

    private void AddCustomXmlPartToWorkbook(Excel.Workbook workbook)
    {
        string xmlString =
            "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
            "<employees xmlns=\"http://schemas.microsoft.com/vsto/samples\">" +
                "<employee>" +
                    "<name>Karina Leal</name>" +
                    "<hireDate>1999-04-01</hireDate>" +
                    "<title>Manager</title>" +
                "</employee>" +
            "</employees>";
    
        Office.CustomXMLPart employeeXMLPart = workbook.CustomXMLParts.Add(xmlString, missing);
    }
    
  2. AddCustomXmlPartToWorkbook 方法加入 Excel VSTO 增益集專案中的 ThisAddIn 類別。

  3. 從專案中的其他程式碼呼叫方法。 例如,若要在使用者開啟活頁簿時建立自訂 XML 組件,請從 WorkbookOpen 事件的事件處理常式呼叫方法。

將自訂 XML 組件加入至 Word 文件

  1. 將新的 CustomXMLPart 物件加入至文件中的 CustomXMLParts 集合。 CustomXMLPart 包含您要儲存在文件中的 XML 字串。

    下列程式碼範例會將自訂 XML 組件加入至指定的文件。

    private void AddCustomXmlPartToActiveDocument(Word.Document document)
    {
        string xmlString =
            "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
            "<employees xmlns=\"http://schemas.microsoft.com/vsto/samples\">" +
                "<employee>" +
                    "<name>Karina Leal</name>" +
                    "<hireDate>1999-04-01</hireDate>" +
                    "<title>Manager</title>" +
                "</employee>" +
            "</employees>";
    
        Office.CustomXMLPart employeeXMLPart = document.CustomXMLParts.Add(xmlString, missing);
    }
    
  2. AddCustomXmlPartToDocument 方法加入 Word VSTO 增益集專案中的 ThisAddIn 類別。

  3. 從專案中的其他程式碼呼叫方法。 例如,若要在使用者開啟文件時建立自訂 XML 組件,請從 DocumentOpen 事件的事件處理常式呼叫方法。

將自訂 XML 組件加入至 PowerPoint 簡報

  1. 將新的 CustomXMLPart 物件新增至簡報中的 Microsoft.Office.Interop.PowerPoint._Presentation.CustomXMLParts 集合。 CustomXMLPart 包含您要儲存在簡報中的 XML 字串。

    下列程式碼範例會將自訂 XML 組件加入至指定的簡報。

    private void AddCustomXmlPartToPresentation(PowerPoint.Presentation presentation)
    {
        string xmlString =
            "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
            "<employees xmlns=\"http://schemas.microsoft.com/vsto/samples\">" +
                "<employee>" +
                    "<name>Karina Leal</name>" +
                    "<hireDate>1999-04-01</hireDate>" +
                    "<title>Manager</title>" +
                "</employee>" +
            "</employees>";
    
        Office.CustomXMLPart employeeXMLPart = 
            presentation.CustomXMLParts.Add(xmlString, missing);
    }
    
  2. AddCustomXmlPartToPresentation 方法加入 PowerPoint VSTO 增益集專案中的 ThisAddIn 類別。

  3. 從專案中的其他程式碼呼叫方法。 例如,若要在使用者開啟文件時建立自訂 XML 組件,請從 Microsoft.Office.Interop.PowerPoint.EApplication_Event.AfterPresentationOpen 事件的事件處理常式呼叫方法。

穩固程式設計

為了簡單起見,這個範例使用定義為方法中區域變數的 XML 字串。 通常,您應從外部來源取得 XML,例如檔案或資料庫。