【问题标题】:Read Excel 2007 Workbook Custom Properties without opening or running macros无需打开或运行宏即可读取 Excel 2007 工作簿自定义属性
【发布时间】:2014-11-19 11:49:07
【问题描述】:

我正在编写一个程序(在 C# 中),如果服务器版本更高,它将能够从服务器替换本地工作簿,然后打开它。为此,我正在尝试阅读本地和服务器副本的自定义属性“修订号”。问题是工作簿包含在打开时启动的宏,我不想运行任何宏来检查修订代码。那么有没有办法在不实际打开的情况下读取 excel 2007 xlsm 文件的修订号?如果没有,有没有办法在 C# 中打开工作簿而不执行它的宏?

【问题讨论】:

标签: excel interop


【解决方案1】:

实际上,我尝试了 tkacprow 的使用 OpenXML 的建议,并且成功了。我只花了一段时间来生成一个工作代码,我昨天才让它工作。 Fratyx,你的小费看起来也很有趣——我会记住的。这是一个工作代码:

public string GetVersion(string fileName)
    {
        string propertyValue = string.Empty;

        try
        {



            using (var wb = SpreadsheetDocument.Open(fileName, false))
            {


                const string corePropertiesSchema = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
                const string dcPropertiesSchema = "http://purl.org/dc/elements/1.1/";
                const string dcTermsPropertiesSchema = "http://purl.org/dc/terms/";




                // Get the core properties part (core.xml).
                CoreFilePropertiesPart xCoreFilePropertiesPart;
                xCoreFilePropertiesPart = wb.CoreFilePropertiesPart;



                // Manage namespaces to perform XML XPath queries.
                NameTable nt = new NameTable();
                XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
                nsManager.AddNamespace("cp", corePropertiesSchema);
                nsManager.AddNamespace("dc", dcPropertiesSchema);
                nsManager.AddNamespace("dcterms", dcTermsPropertiesSchema);

                // Get the properties from the package.
                XmlDocument xdoc = new XmlDocument(nt);

                // Load the XML in the part into an XmlDocument instance.
                xdoc.Load(xCoreFilePropertiesPart.GetStream());

                string searchString = string.Format("//cp:coreProperties/{0}", "cp:version");

                XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);
                if (!(xNode == null))
                {
                    //Console.WriteLine(" version is " +  xNode.InnerText);
                    propertyValue = xNode.InnerText;
                }



            }


        }


        catch (OpenXmlPackageException e)
        {

            throw new ApplicationException(String.Format("Incorrect Format detected in a file: {0}" , fileName),e.GetBaseException());
        }


        return propertyValue;

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    相关资源
    最近更新 更多