在.NET中创build的OpenXML电子表格不会在iPad中打开

我试图在.NET中生成一个电子表格,当他不在办公室时,我的经理将在iPad上打开电子表格。

电子表格可以在Windows PC上打开,但是当试图在iPad上打开时,它会显示“读取文档时发生错误”(太有用了!)

通过使用OpenXML SDK生产力工具上的“比较”function以及在iPad 打开的文档,并通过在记事本中对错误文档的XML文件进行手动编辑,我已将其缩小到文件xl / _rels / workbook .xml.rels存储工作簿中各个部分的关系。

这是我用来生成WorkbookPart和引用的代码

WorkbookPart workbookPart1 = document.AddWorkbookPart(); WorkbookStylesPart workbookStylesPart1 = workbookPart1.AddNewPart<WorkbookStylesPart>("rId3"); ThemePart themePart1 = workbookPart1.AddNewPart<ThemePart>("rId2"); WorksheetPart worksheetPart1 = workbookPart1.AddNewPart<WorksheetPart>("rId1"); 

我的代码生成以下输出,它不会在iPad上打开。

  <?xml version="1.0" encoding="utf-8" ?> <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="/xl/styles.xml" Id="rId3" /> <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="/xl/theme/theme.xml" Id="rId2" /> <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="/xl/worksheets/sheet.xml" Id="rId1" /> </Relationships> 

如果我将Target属性的值更改为使用相对引用path,并给出以下输出,则它将在iPad上打开。

  <?xml version="1.0" encoding="utf-8" ?> <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml" Id="rId3" /> <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme.xml" Id="rId2" /> <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet.xml" Id="rId1" /> </Relationships> 

所以问题是:
如何更改我的.NET代码,以便输出具有相对path的XML的第二个版本。

所有的帮助,感激地收到!

我花了很多时间研究这个,并认为我会分享我的结果。 看来OpenXML正在做两件事情。 1. content_types.xml文件缺less工作簿2的条目。xl / _rels / workbook.xml.rels文件正在使用完整的相对path。

Excel本身打开文件很好,但我已经尝试了iPad上的各种应用程序,他们都失败了。 所以我必须使用下面的代码自己手动修复这些文件。 它假定文件的全部内容以stream的forms传递,并使用DotNetZip打开和操作。 希望这段代码能够帮助别人

  private Stream ApplyOpenXmlFix(Stream input) { const string RELS_FILE = @"xl/_rels/workbook.xml.rels"; const string RELATIONSHIP_ELEMENT = "Relationship"; const string CONTENT_TYPE_FILE = @"[Content_Types].xml"; const string XL_WORKBOOK_XML = "/xl/workbook.xml"; const string TARGET_ATTRIBUTE = "Target"; const string SUPERFLUOUS_PATH = "/xl/"; const string OVERRIDE_ELEMENT = "Override"; const string PARTNAME_ATTRIBUTE = "PartName"; const string CONTENTTYPE_ATTRIBUTE = "ContentType"; const string CONTENTTYPE_VALUE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"; XNamespace contentTypesNamespace = "http://schemas.openxmlformats.org/package/2006/content-types"; XNamespace relsNamespace = "http://schemas.openxmlformats.org/package/2006/relationships"; XDocument xlDocument; MemoryStream memWriter; try { input.Seek(0, SeekOrigin.Begin); ZipFile zip = ZipFile.Read(input); //First we fix the workbook relations file var workbookRelations = zip.Entries.Where(e => e.FileName == RELS_FILE).Single(); xlDocument = XDocument.Load(workbookRelations.OpenReader()); //Remove the /xl/ relative path from all target attributes foreach (var relationship in xlDocument.Root.Elements(relsNamespace + RELATIONSHIP_ELEMENT)) { var target = relationship.Attribute(TARGET_ATTRIBUTE); if (target != null && target.Value.StartsWith(SUPERFLUOUS_PATH)) { target.Value = target.Value.Substring(SUPERFLUOUS_PATH.Length); } } //Replace the content in the source zip file memWriter = new MemoryStream(); xlDocument.Save(memWriter, SaveOptions.DisableFormatting); memWriter.Seek(0, SeekOrigin.Begin); zip.UpdateEntry(RELS_FILE, memWriter); //Now we fix the content types XML file var contentTypeEntry = zip.Entries.Where(e => e.FileName == CONTENT_TYPE_FILE).Single(); xlDocument = XDocument.Load(contentTypeEntry.OpenReader()); if (!xlDocument.Root.Elements().Any(e => e.Name == contentTypesNamespace + OVERRIDE_ELEMENT && e.Attribute(PARTNAME_ATTRIBUTE) != null && e.Attribute(PARTNAME_ATTRIBUTE).Value == XL_WORKBOOK_XML)) { //Add in the missing element var overrideElement = new XElement( contentTypesNamespace + OVERRIDE_ELEMENT, new XAttribute(PARTNAME_ATTRIBUTE, XL_WORKBOOK_XML), new XAttribute(CONTENTTYPE_ATTRIBUTE, CONTENTTYPE_VALUE)); xlDocument.Root.Add(overrideElement); //Replace the content memWriter = new MemoryStream(); xlDocument.Save(memWriter, SaveOptions.DisableFormatting); memWriter.Seek(0, SeekOrigin.Begin); zip.UpdateEntry(CONTENT_TYPE_FILE, memWriter); } Stream output = new MemoryStream(); //Save file zip.Save(output); return output; } catch { //Just in case it fails, return the original document return input; } } 

Comradsky发送PDF的答案是一个好主意,但如果有人需要解决这个问题,我已经提出了一个解决scheme。 我知道这是一个可怕的黑客,但它的工作,我已经花了几个小时试图find一个方法来做到“合法”,无济于事。

它涉及打开.rels文件并在closures文档后直接编辑文件内的xml。

  public static void MakeRelativePaths(string filepath) { // Get the namespace strings const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; const string relationshipSchema = "http://schemas.openxmlformats.org/package/2006/relationships"; string documentUri = null; string documentDirectory = null; string documentName = null; Uri relDocUri = null; XName targetAttributeName = null; string targetValue = null; // Open the package using (Package xlPackage = Package.Open(filepath, FileMode.Open, FileAccess.ReadWrite)) { // Get the directory and filename of the main document part (eg /xl/workbook.xml). foreach (System.IO.Packaging.PackageRelationship relationship in xlPackage.GetRelationshipsByType(documentRelationshipType)) { documentUri = relationship.TargetUri.ToString(); documentName = System.IO.Path.GetFileName(documentUri); documentDirectory = documentUri.Substring(0, documentUri.Length - documentName.Length); // There should only be document part in the package, but break out anyway. break; } // Load the relationship document relDocUri = new Uri(documentDirectory + "_rels/" + documentName + ".rels", UriKind.Relative); XDocument relDoc = XDocument.Load(xlPackage.GetPart(relDocUri).GetStream()); // Loop through all of the relationship nodes targetAttributeName = XName.Get("Target"); foreach (XElement relNode in relDoc.Elements(XName.Get("Relationships", relationshipSchema)).Elements(XName.Get("Relationship", relationshipSchema))) { // Edit the value of the Target attribute targetValue = relNode.Attribute(targetAttributeName).Value; if (targetValue.StartsWith(documentDirectory)) targetValue = targetValue.Substring(documentDirectory.Length); relNode.Attribute(targetAttributeName).Value = targetValue; } // Save the document relDoc.Save(xlPackage.GetPart(relDocUri).GetStream()); } } 

创build完成后,您可以尝试validationOpenXML电子表格:

 using System; using System.Collections.Generic; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; using (OpenXmlPackage document = SpreadsheetDocument.Open(spreadsheetPathToValidate, false)) { var validator = new OpenXmlValidator(); IEnumerable<ValidationErrorInfo> errors = validator.Validate(document); foreach (ValidationErrorInfo info in errors) { try { Console.WriteLine("Validation information: {0} {1} in {2} part (path {3}): {4}", info.ErrorType, info.Node.GetType().Name, info.Part.Uri, info.Path.XPath, info.Description); } catch (Exception ex) { Console.WriteLine("Validation failed: {0}", ex); } } } 

希望有所帮助,

我也一直在努力解决类似的问题。 我终于想出了一个可行的解决scheme。 这是我写的解决问题的代码

  // Add a new worksheet part to the workbook. WorksheetPart newWorksheetPart = _document.WorkbookPart.AddNewPart<WorksheetPart>(); newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData()); Sheets sheets = _document.WorkbookPart.Workbook.GetFirstChild<Sheets>(); string relationshipId = _document.WorkbookPart.GetIdOfPart(newWorksheetPart); //This bit is required for iPad to be able to read the sheets inside the xlsx file. The file will still work fine in Excel string relationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"; _document.Package.GetPart(_document.WorkbookPart.Uri).CreateRelationship(new Uri(newWorksheetPart.Uri.OriginalString.Replace("/xl/", String.Empty).Trim(), UriKind.Relative), TargetMode.Internal, relationshipType); _document.Package.GetPart(_document.WorkbookPart.Uri).DeleteRelationship(relationshipId); PackageRelationshipCollection sheetRelationships = _document.Package.GetPart(_document.WorkbookPart.Uri).GetRelationshipsByType(relationshipType); relationshipId = sheetRelationships.Where(f => f.TargetUri.OriginalString == newWorksheetPart.Uri.OriginalString.Replace("/xl/", String.Empty).Trim()).Single().Id; // Get a unique ID for the new sheet. uint sheetId = 1; if (sheets.Elements<Sheet>().Count() > 0) sheetId = sheets.Elements<Sheet>().Max(s => s.SheetId.Value) + 1; // Append the new worksheet and associate it with the workbook. Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName }; sheets.Append(sheet); _worksheets.Add(new Worksheet(newWorksheetPart.Worksheet, sheetId)); 

_document和_worksheets,是我的解决scheme类中的私有variables。