添加自定义 XML 部件并按 ID 选择它们

可能的使用场景

自定义 XML 部件是存储在 Microsoft Excel 文档中并由处理它们的应用程序使用的 XML 数据。目前没有使用 Microsoft Excel UI 直接添加它们的方法。但是,您可以通过各种方式以编程方式添加它们,例如使用VSTO, 使用Aspose.Cells等请使用Workbook.getCustomXmlParts().add() 方法,如果你想使用 Aspose.Cells API 添加自定义 XML 部件。你也可以设置它的 ID,使用CustomXmlPart.ID财产。同样,如果你想通过 ID 选择 Custom XML Part,你可以使用[工作簿.getCustomXmlParts().selectByID()](https://reference.aspose.com/cells/java/com.aspose.cells/customxmlpartcollection#selectByID(java.lang.String)) 方法。

添加自定义 XML 部件并按 ID 选择它们

以下示例代码首先添加四个自定义 XML 部件,使用[Workbook.getCustomXmlParts().add()](https://reference.aspose.com/cells/java/com.aspose.cells/customxmlpartcollection#add(java.lang.Object)) 方法。然后它使用设置他们的IDCustomXmlPart.ID财产。最后,它使用以下方法查找或选择添加的自定义 XML 部件之一[工作簿.getCustomXmlParts().selectByID()](https://reference.aspose.com/cells/java/com.aspose.cells/customxmlpartcollection#selectByID(java.lang.String)) 方法。另请参阅下面给出的代码的控制台输出以供参考。

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Create empty workbook.
Workbook wb = new Workbook();
// Some data in the form of byte array.
// Please use correct XML and Schema instead.
byte[] btsData = new byte[] { 1, 2, 3 };
byte[] btsSchema = new byte[] { 1, 2, 3 };
// Create four custom xml parts.
wb.getCustomXmlParts().add(btsData, btsSchema);
wb.getCustomXmlParts().add(btsData, btsSchema);
wb.getCustomXmlParts().add(btsData, btsSchema);
wb.getCustomXmlParts().add(btsData, btsSchema);
// Assign ids to custom xml parts.
wb.getCustomXmlParts().get(0).setID("Fruit");
wb.getCustomXmlParts().get(1).setID("Color");
wb.getCustomXmlParts().get(2).setID("Sport");
wb.getCustomXmlParts().get(3).setID("Shape");
// Specify search custom xml part id.
String srchID = "Fruit";
srchID = "Color";
srchID = "Sport";
// Search custom xml part by the search id.
CustomXmlPart cxp = wb.getCustomXmlParts().selectByID(srchID);
// Print the found or not found message on console.
if (cxp == null)
{
System.out.println("Not Found: CustomXmlPart ID " + srchID);
}
else
{
System.out.println("Found: CustomXmlPart ID " + srchID);
}

控制台输出

Found: CustomXmlPart ID Sport