HOW TO:將自訂 XML 組件加入至文件層級自訂
您可以在文件層級自訂中建立自訂 XML 組件,將 XML 資料儲存在 Microsoft Office Excel 活頁簿 (Workbook) 或 Microsoft Office Word 文件。 如需詳細資訊,請參閱 自訂 XML 組件概觀。
**適用於:**本主題中的資訊適用於下列應用程式的文件層級專案:Excel 2007 和 Excel 2010、Word 2007 和 Word 2010。如需詳細資訊,請參閱依 Office 應用程式和專案類型提供的功能。
![]() |
---|
Visual Studio 不提供 Microsoft Office PowerPoint 的文件層級專案。 如需使用應用程式層級增益集將自訂 XML 組件加入至 PowerPoint 簡報的詳細資訊,請參閱 HOW TO:使用應用程式層級增益集將自訂 XML 組件加入至文件。 |
若要將自訂 XML 組件加入至 Excel 活頁簿
將新的 CustomXMLPart 物件加入至活頁簿中的 CustomXMLParts 集合。 CustomXMLPart 包含您要儲存在活頁簿中的 XML 字串。
Private Sub AddCustomXmlPartToWorkbook() Dim xmlString As String = _ "<?xml version=""1.0"" encoding=""utf-8"" ?>" & _ "<employees https://schemas.microsoft.com/vsto/samples"">" & _ "<employee>" & _ "<name>Karina Leal</name>" & _ "<hireDate>1999-04-01</hireDate>" & _ "<title>Manager</title>" & _ "</employee>" & _ "</employees>" Dim employeeXMLPart As Office.CustomXMLPart = Me.CustomXMLParts.Add(xmlString) End Sub
private void AddCustomXmlPartToWorkbook() { string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<employees xmlns=\"https://schemas.microsoft.com/vsto/samples\">" + "<employee>" + "<name>Karina Leal</name>" + "<hireDate>1999-04-01</hireDate>" + "<title>Manager</title>" + "</employee>" + "</employees>"; Office.CustomXMLPart employeeXMLPart = this.CustomXMLParts.Add(xmlString, missing); }
將 AddCustomXmlPartToWorkbook 方法加入至 Excel 文件層級專案中的 ThisWorkbook 類別。
從您的專案中其他程式碼呼叫方法。 例如,若要在使用者開啟活頁簿時建立自訂 XML 組件,請從 ThisWorkbook_Startup 事件處理常式呼叫方法。
若要將自訂 XML 組件加入至 Word 文件
將新的 CustomXMLPart 物件加入至文件中的 CustomXMLParts 集合。 CustomXMLPart 包含您要儲存在文件中的 XML 字串。
Private Sub AddCustomXmlPartToDocument() Dim xmlString As String = _ "<?xml version=""1.0"" encoding=""utf-8"" ?>" & _ "<employees https://schemas.microsoft.com/vsto/samples"">" & _ "<employee>" & _ "<name>Karina Leal</name>" & _ "<hireDate>1999-04-01</hireDate>" & _ "<title>Manager</title>" & _ "</employee>" & _ "</employees>" Dim employeeXMLPart As Office.CustomXMLPart = _ Me.CustomXMLParts.Add(xmlString) End Sub
private void AddCustomXmlPartToDocument() { string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<employees xmlns=\"https://schemas.microsoft.com/vsto/samples\">" + "<employee>" + "<name>Karina Leal</name>" + "<hireDate>1999-04-01</hireDate>" + "<title>Manager</title>" + "</employee>" + "</employees>"; Office.CustomXMLPart employeeXMLPart = this.CustomXMLParts.Add(xmlString, missing); }
將 AddCustomXmlPartToDocument 方法加入至 Word 文件層級專案中的 ThisDocument 類別。
從您的專案中其他程式碼呼叫方法。 例如,若要在使用者開啟文件時建立自訂 XML 組件,請從 ThisDocument_Startup 事件處理常式呼叫方法。
穩固程式設計
為了簡化,這個範例使用定義為方法中區域變數的 XML 字串。 通常,您應從外部來源取得 XML,例如檔案或資料庫。
請參閱
工作
HOW TO:使用應用程式層級增益集將自訂 XML 組件加入至文件
HOW TO:將自訂 XML 組件加入至文件而不啟動 Microsoft Office