【问题标题】:Check Xelement style in OpenXml检查 OpenXml 中的 Xelement 样式
【发布时间】:2016-03-11 05:11:28
【问题描述】:

我将所有内容从 OpenXml 字文件复制到另一个 OpenXml 字文件。 但是在复制过程中,我想根据样式进行一些更改。 例如,如果某个段落内的文本是红色的,我会将其更改为蓝色。

如何获取特定段落的样式?

我使用此代码来遍历所有段落并复制到其他文件:

byte[] docByteArray = File.ReadAllBytes(HttpContext.Current.Server.MapPath("\\")
    + "\\from.docx");
using (MemoryStream memoryStream = new MemoryStream())
{
    memoryStream.Write(docByteArray, 0, docByteArray.Length);
    using (WordprocessingDocument doc =
    WordprocessingDocument.Open(memoryStream, true))
    {
        RevisionAccepter.AcceptRevisions(doc);
        XElement root = doc.MainDocumentPart.GetXDocument().Root;
        XElement body = root.LogicalChildrenContent().First();
        foreach (XElement blockLevelContentElement in body.LogicalChildrenContent())
        {
            if (blockLevelContentElement.Name == W.p)
            {
                var text = blockLevelContentElement
                    .LogicalChildrenContent()
                    .Where(e => e.Name == W.r)
                    .LogicalChildrenContent()
                    .Where(e => e.Name == W.t)
                    .Select(t => (string)t)
                    .StringConcatenate();

                //addToOtherDocCode().....
            }
        }
    }
}

所以当我确定元素是段落时,我可以循环里面的所有运行,但我怎样才能获得它的样式(颜色、粗体、斜体、大小......)?

【问题讨论】:

    标签: c# .net ms-word openxml xelement


    【解决方案1】:

    样式在 ParagaphProperties 元素内部 w:color 是颜色,w:b 表示粗体,等等。

    https://msdn.microsoft.com/EN-US/library/office/documentformat.openxml.wordprocessing.paragraphproperties.aspx

    以下获取段落属性的 xml 和该段落的文本,希望这会有所帮助!

    byte[] docByteArray = File.ReadAllBytes("testDoc.docx");
    using (MemoryStream memoryStream = new MemoryStream())
    {
        memoryStream.Write(docByteArray, 0, docByteArray.Length);
        using (WordprocessingDocument doc =
        WordprocessingDocument.Open(memoryStream, true))
        {
            var body = doc.MainDocumentPart.Document.Body;
            var paragraphs = new List<Paragraph>();
    
            foreach(Paragraph paragraph in body.Descendants<Paragraph>()
                .Where(e => e.ParagraphProperties != null))
            {
                if(paragraph.ParagraphProperties.ParagraphMarkRunProperties != null)
                {
                    foreach(OpenXmlElement element in paragraph.ParagraphProperties.ParagraphMarkRunProperties.ChildElements)
                    {
                        Console.WriteLine(element.OuterXml);
                    }
                }
    
                Console.WriteLine(paragraph.InnerText);
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多