6

我正在尝试在 .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 的第二个版本。

感谢所有帮助!

4

5 回答 5

6

我花了很多时间研究这个,并认为我会分享我的结果。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;
        }
    }
于 2013-11-21T15:08:25.017 回答
2

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

它涉及打开 .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());
        }
    }
于 2012-06-08T07:17:51.183 回答
2

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

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

于 2013-03-20T13:01:30.193 回答
0

您可以尝试在创建 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);
        }
    }
}

希望有帮助,

于 2012-06-07T13:24:57.917 回答
0

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

于 2019-01-10T13:41:44.603 回答