检查OpenXml中的Xelement样式

时间:2015-12-06 15:50:01

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

我将OpenXml word文件中的所有内容复制到另一个OpenXml word文件中。 但在复制期间,我想根据风格做一些改变。 对于Examlpe,如果某段内的文字为红色,我会将其改为蓝色。

如何获得特定的段落运行风格?

我使用此代码预先处理所有段落并复制到其他文件:

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().....
            }
        }
    }
}

因此,当我确定该元素是段落时,我可以循环所有内部运行但是如何才能获得它的样式(颜色,粗体,斜体,大小......)?

1 个答案:

答案 0 :(得分:1)

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

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

以下为该paragaph的paragaph属性和文本获取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);
            }
        }
    }
}