• 如何:修改 Office Open XML 文档【转载】


    全文转载自:http://msdn.microsoft.com/zh-cn/library/bb669125.aspx

    本主题显演示一个打开、修改和保存 Office Open XML 文档的示例。

    有关 Office Open XML 的更多信息,请参见 www.openxmldeveloper.org(可能为英文网页)。

    示例

    本示例查找文档中的第一个段落元素。 示例从段落中检索文本,然后删除段落中的所有文本域。 它创建一个由第一个段落已转换为大写的文本构成的新文本域。 然后将已更改的 XML 序列化为 Open XML 包并关闭该包。

    本示例使用 WindowsBase 程序集中的类。 它使用 System.IO.Packaging 命名空间中的类型。

    public static class LocalExtensions
    {
        public static string StringConcatenate(this IEnumerable<string> source)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in source)
                sb.Append(s);
            return sb.ToString();
        }
    
        public static string StringConcatenate<T>(this IEnumerable<T> source,
            Func<T, string> func)
        {
            StringBuilder sb = new StringBuilder();
            foreach (T item in source)
                sb.Append(func(item));
            return sb.ToString();
        }
    
        public static string StringConcatenate(this IEnumerable<string> source, string separator)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in source)
                sb.Append(s).Append(separator);
            return sb.ToString();
        }
    
        public static string StringConcatenate<T>(this IEnumerable<T> source,
            Func<T, string> func, string separator)
        {
            StringBuilder sb = new StringBuilder();
            foreach (T item in source)
                sb.Append(func(item)).Append(separator);
            return sb.ToString();
        }
    }
    
    class Program
    {
        public static string ParagraphText(XElement e)
        {
            XNamespace w = e.Name.Namespace;
            return e
                   .Elements(w + "r")
                   .Elements(w + "t")
                   .StringConcatenate(element => (string)element);
        }
    
        static void Main(string[] args)
        {
            const string fileName = "SampleDoc.docx";
    
            const string documentRelationshipType =
              "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
            const string stylesRelationshipType =
              "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
            const string wordmlNamespace =
              "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
            XNamespace w = wordmlNamespace;
    
            using (Package wdPackage = Package.Open(fileName, FileMode.Open, FileAccess.ReadWrite))
            {
                PackageRelationship docPackageRelationship =
                  wdPackage.GetRelationshipsByType(documentRelationshipType).FirstOrDefault();
                if (docPackageRelationship != null)
                {
                    Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative),
                      docPackageRelationship.TargetUri);
                    PackagePart documentPart = wdPackage.GetPart(documentUri);
    
                    //  Load the document XML in the part into an XDocument instance.
                    XDocument xDoc = XDocument.Load(XmlReader.Create(documentPart.GetStream()));
    
                    //  Find the styles part. There will only be one.
                    PackageRelationship styleRelation =
                      documentPart.GetRelationshipsByType(stylesRelationshipType).FirstOrDefault();
                    PackagePart stylePart = null;
                    XDocument styleDoc = null;
    
                    if (styleRelation != null)
                    {
                        Uri styleUri = PackUriHelper.ResolvePartUri(documentUri, styleRelation.TargetUri);
                        stylePart = wdPackage.GetPart(styleUri);
    
                        //  Load the style XML in the part into an XDocument instance.
                        styleDoc = XDocument.Load(XmlReader.Create(stylePart.GetStream()));
                    }
    
                    XElement paraNode = xDoc
                                        .Root
                                        .Element(w + "body")
                                        .Descendants(w + "p")
                                        .FirstOrDefault();
    
                    string paraText = ParagraphText(paraNode);
    
                    // remove all text runs
                    paraNode.Descendants(w + "r").Remove();
    
                    paraNode.Add(
                        new XElement(w + "r",
                            new XElement(w + "t", paraText.ToUpper())
                        )
                    );
    
                    //  Save the XML into the package
                    using (XmlWriter xw =
                      XmlWriter.Create(documentPart.GetStream(FileMode.Create, FileAccess.Write)))
                    {
                        xDoc.Save(xw);
                    }
    
                    Console.WriteLine("New first paragraph: >{0}<", paraText.ToUpper());
                }
            }
        }
    }
    本文由作者:陈希章 于 2009/7/16 10:54:50 发布在:http://www.cnblogs.com/chenxizhang/
    本文版权归作者所有,可以转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    更多博客文章,以及作者对于博客引用方面的完整声明以及合作方面的政策,请参考以下站点:陈希章的博客中心
  • 相关阅读:
    斯坦福大学Andrew Ng教授主讲的《机器学习》公开课观后感
    关于内推,你该知道的点点滴滴
    向大学说拜拜——大学 > 兴趣 + 时间 + 思考 + 实践
    源码浅析:InnoDB聚集索引如何定位到数据的物理位置,并从磁盘读取
    5.7.17版本mysqlbinlog实时拉取的二进制日志不完整的原因分析
    InnoDB的ibd数据文件为什么比data_length+index_length+data_free的总和还要大?
    gh-ost工具在线改表过程的详细解析
    MySQL5.7 使用utf8mb4字符集比latin1字符集性能低25%,你敢信?
    通过slow query log可以查出长时间未提交的事务吗?用实验+源码来揭晓答案
    源码浅析:MySQL一条insert操作,会写哪些文件?包括UNDO相关的文件吗?
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1524655.html
Copyright © 2020-2023  润新知