c# - 无效超链接 : Malformed URI is embedded as a hyperlink in the document

标签 c# openxml excel-addins

我在应用程序中使用 OpenXml 命名空间。我用它来读取 Excel 文件中的 XML。这对于某些 Excel 文件工作正常,但在其他文件上我收到运行时错误,提示

Invalid Hyperlink: Malformed URI is embedded as a hyperlink in the document.

我在下面一行得到运行时间

using (var spreadsheet = 
      DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(filePathCopy, true))

我不确定为什么它适用于某些 Excel 文件而不适用于其他文件。

最佳答案

解决方案来自 Eric White 的 blog post


  1. 从 Nuget 导入 OpenXmlPowerTools 并使用它。

    using OpenXmlPowerTools;
    

    所需的方法是OpenXmlPowerTools.UriFixer.FixInvalidUri,或者您可以从链接复制UriFixer类。


  • 添加 FixUri() 方法,以使用新定义的 URI 处理损坏的 URI。

    private static Uri FixUri(string brokenUri)
    {
        return new Uri("http://broken-link/");
    }
    

  • 添加代码以打开文档,如果发生异常,它将修复 URI 并重新打开修复的文档。

    WordprocessingDocument wDoc;
    try
    {
        using (wDoc = WordprocessingDocument.Open(newFileName, true))
        {
            //Try do something
        }
    }
    catch (OpenXmlPackageException e)
    {
        if (e.ToString().Contains("Invalid Hyperlink"))
        {
            using (FileStream fs = new FileStream(newFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                //Fix problematic URI's
                UriFixer.FixInvalidUri(fs, brokenUri => FixUri(brokenUri));
            }
            using (wDoc = WordprocessingDocument.Open(newFileName, true))
            {
                //Do something without error
            }
        }
    }
    
  • 关于c# - 无效超链接 : Malformed URI is embedded as a hyperlink in the document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979946/

    相关文章:

    javascript - 为什么在尝试锁定或解锁 Excel API 中的一系列单元格时出现 AccessDenied

    c# - BindingExpression 路径错误 : property not found on 'object'

    c# - 使用 Open Xml 将列添加到现有 Excel 2007 工作簿

    wpf - 强制关闭 Excel 时如何禁止禁用加载项对话框

    excel - 无论如何要在 Excel Javascript API 中获取单元格先例和从属?

    c# - 有没有办法使用 OpenXml 从列中获取最后填充的行单元格值

    c# - 在 C# 中格式化字符串

    c# - 如何? : if table doesn't exist on database, 使用 DataReader 创建

    c# - WPF 的最佳实践 - 每个 GUI 元素都需要绑定(bind)吗?

    c# - OpenXML - 将日期写入 Excel 电子表格会导致内容不可读