在OpenXML中使用XML映射导入xml

我一直在尝试使用OpenXML SDK中的xml映射将XML数据导入Excel。

我find了使用Excel Interop做这个的多个例子,但是没有使用SDK。 作为一个侧面说明,我有这个工作的Word文件,但程序是不一样的Excel(Word中的CustomXmlPart,Excel中的CustomXmlMappingPart)。

也许这是不可能直接使用SDK的。 解决方法可能是使用命名范围,但我觉得不太实际。

编辑:场景使用带有XML映射的Excel文件(按照所述创buildhttps://support.office.com/zh-cn/article/Import-XML-data-6eca3906-d6c9-4f0d-b911- c736da817fa4?ui = en-US&rs = en-US&ad = US )作为“模板”来填充数据。 可以是客户名称,当前date或类似的。

我尝试过类似的东西。 与Word相比,映射显示在CustomXmlMappingsPart中。

using (var fileStream = File.Open(@"c:\temp\test.xslx", FileMode.Open)) { SpreadsheetDocument excelDoc = SpreadsheetDocument.Open(fileStream, true); // Only one mapping // When doing this for word, there is a document.MainDocumentPart.CustomXmlParts var mapping = excelDoc.WorkbookPart.GetPartsOfType<CustomXmlMappingsPart>().FirstOrDefault(); XNamespace mappingNS = "http://demoimport.org/xmlimport"; var xmlData = new XElement(mappingNS + "ImportRoot", new XElement(mappingNS + "Customer", "Test Customer Name")); XmlReader reader = xmlData.CreateReader(); reader.MoveToContent(); using (MemoryStream ms = new MemoryStream()) { xmlData.Save(ms); ms.Position = 0; // Corrupts the file // Probably due to CustomXmlMappingsPart mapping.FeedData(ms); } } 

免责声明 – 我不知道这是如何做到这一点,但下面的作品为我的有限使用情况

我没有直接使用XML映射部分( CustomXmlMappingsPart ), CustomXmlMappingsPart使用Open XML Productivity Tool,发现映射的单元格包含用于SingleCellTablePart集合中的映射的XPath。

可以遍历所有的SingleCellTablePart在XML文件中查找匹配的元素。 我从https://simpleooxml.codeplex.com/发现了一个非常有用的扩展,将数据写入文档&#x3002; 完全可以实现只使用OpenXML SDK。 但是我发现使用SDK设置单元格值并不是一个微不足道的,因为人们会想到。

 using (var fileStream = File.Open(@"c:\temp\test.xlsx", FileMode.Open)) { /* Simple xml-file, * <General> * <Customer>Demo Customer</Customer> * </General> */ XDocument doc = XDocument.Load(@"c:\temp\demodata.xml"); SpreadsheetDocument excelDoc = SpreadsheetDocument.Open(fileStream, true); foreach (var workSheet in excelDoc.WorkbookPart.WorksheetParts) { // Note, multiple mappings could exist. For simplicity I expect only one var mappings = workSheet.GetPartsOfType<SingleCellTablePart>().FirstOrDefault(); if (mappings == null) continue; foreach (SingleXmlCell cellMapping in mappings.SingleXmlCells) { if (cellMapping.XmlCellProperties != null && cellMapping.XmlCellProperties.XmlProperties != null) { // cellMapping.XmlCellProperties.XmlProperties.XPath = /General/Customer var matchingNode = doc.XPathSelectElement(cellMapping.XmlCellProperties.XmlProperties.XPath); if(matchingNode != null && !string.IsNullOrEmpty(matchingNode.Value)) { // If a maching node exist, set text value from XML-file // SpreadsheetReader and WorksheetWriter from https://simpleooxml.codeplex.com/ string column = SpreadsheetReader.ColumnFromReference(cellMapping.CellReference.Value); uint row = SpreadsheetReader.RowFromReference(cellMapping.CellReference.Value); WorksheetWriter.PasteText(excelDoc, workSheet, column, row, matchingNode.Value); } } } WorksheetWriter.Save(excelDoc, workSheet); } }