【问题标题】:OpenXML spreadsheet created in .NET won't open in iPad在 .NET 中创建的 OpenXML 电子表格无法在 iPad 中打开
【发布时间】:2012-06-11 08:16:23
【问题描述】:

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

电子表格在 Windows PC 上可以正常打开,但尝试在 iPad 上打开时显示“读取文档时出错”(非常有用!)

通过使用 OpenXML SDK Productivity 工具上的“比较”功能与在 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 属性的值更改为使用相对引用路径,并给出以下输出,那么它确实会在 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 代码,使其输出带有相对路径的 XML 的第二个版本。

感谢所有帮助!

【问题讨论】:

  • 这似乎更像是一个“如何使用”的问题,而不是一个编程问题,但无论如何,您尝试使用 iPad 上的哪个应用程序打开电子表格?
  • 对不起,我不明白您所说的“如何使用”与编程是什么意思,但还是感谢您回答我。我只是通过电子邮件直接从 ipad 上的邮件应用程序打开它。
  • 我也有同样的问题,但是文档中没有关系文件,也没有任何Target属性!

标签: .net ios ipad openxml relative-path


【解决方案1】:

我花了很多时间研究这个,并认为我会分享我的结果。 OpenXML 似乎在做两件事。 1. content_types.xml 文件缺少工作簿的条目 2. xl/_rels/workbook.xml.rels 文件使用完全相对路径。

Excel 本身可以正常打开文件,但我在 iPad 上尝试了各种应用程序,但都失败了。所以我不得不使用以下代码自己手动修复文件。它假定文件的全部内容作为流传入并使用 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;
        }
    }

【讨论】:

    【解决方案2】:

    Comradsky 发送 pdf 的答案是个好主意,但如果有人需要解决这个问题,我想出了一个解决方案。我知道这是一个可怕的 hack,但它确实有效,我花了几个小时试图找到一种“合法”的方法,但无济于事。

    它涉及打开 .rels 文件并在文档关闭后直接编辑文件中的 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 (e.g. /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());
            }
        }
    

    【讨论】:

    • 我遇到了完全相同的问题 - 我已经尝试实现这一点,但我在流中使用文档,而不是 IO。没有运气让它去。您的代码运行,我希望它在比较提取的文件后工作。如果您能提供帮助,我们将不胜感激。
    【解决方案3】:

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

            // 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 是我的解决方案类中的私有变量。

    【讨论】:

      【解决方案4】:

      您可以尝试在创建 OpenXML 电子表格后对其进行验证:

      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);
              }
          }
      }
      

      希望对你有帮助,

      【讨论】:

      • 它验证成功。如果我使用 SDK 生产力工具中的验证工具,它也可以成功验证。另外,我需要一种方法来实际更改它 - 我可以在代码中看到关系的 URI 字段,但它是只读的。
      【解决方案5】:

      我遇到了同样的问题。在 Cell 上填写 CellReference 属性后,它开始为我工作。在 CellReference 中,您只需输入单元格的名称,例如“A1”、“B1”、...、“C123”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-10
        • 1970-01-01
        • 2013-07-08
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        相关资源
        最近更新 更多