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

我与影子孤独终老i 提交于 2020-04-09 20:31:03

问题


I'm using the OpenXml namespace in my application. I'm using this to read the XML within an Excel file. This works fine with certain excel files but on others I get a run time error saying

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

I get the run time on the following line

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

I'm not sure why it works for some Excel files and doesn't work on others.


回答1:


Solution is from Eric White's blog post.

  1. Import OpenXmlPowerTools from Nuget and use it.

    using OpenXmlPowerTools;
    

    This is needed for the function OpenXmlPowerTools.UriFixer, unless you want to copy the function from the link.


  2. Add the FixUri() Function to handle the broken URI's with a new defined URI.

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


  3. Add code to open the document, if the exception occurs it fixes the URI's and re-opens the fixed document.

    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
                OpenXmlPowerTools.UriFixer.FixInvalidUri(fs, brokenUri => FixUri(brokenUri));
            }
            using (wDoc = WordprocessingDocument.Open(newFileName, true))
            {
                //Do something without error
            }
        }
    }
    


来源:https://stackoverflow.com/questions/40979946/invalid-hyperlink-malformed-uri-is-embedded-as-a-hyperlink-in-the-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!