从strings数组创建docx段落

时间:2011-08-22 11:20:38

标签: c# openxml-sdk docx

我在文档占位符中有一些文本。此文本由多个字符串组成,由“<line>”拆分。如何用段落的scoupe替换这个文本,每个段落只包含一个字符串?


1 个答案:

答案 0 :(得分:1)

我找到了解决方案。只需要打破字符串,并为每个字符串创建一个带格式的段落,否则元素将创建为OpenXmlUnknownElement。

   XDocument customXml = GenerateXmlForReport(report);
            String customXmlId = AddCustomXml(document, customXml);
            DataBind(document, customXml, customXmlId);
            document.MainDocumentPart.Document.Body.GetFirstChild<SdtBlock>().RemoveAllChildren();
            string[] lines = Regex.Split(report.ReportTextBody, "</line>");
            foreach (var line in lines)
            {
                Paragraph p = new Paragraph();
                ParagraphProperties paragraphProperties1 = new ParagraphProperties();
                ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "BodyText" };
                ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
                RunFonts runFonts1 = new RunFonts() { Ascii = "Arial", HighAnsi = "Arial" };
                paragraphMarkRunProperties1.Append(runFonts1);
                paragraphProperties1.Append(paragraphStyleId1);
                paragraphProperties1.Append(paragraphMarkRunProperties1);
                RunProperties runProperties1 = new RunProperties();
                RunStyle runStyle1 = new RunStyle() { Val = "PlaceholderText" };

                runProperties1.Append(runStyle1);
                Run run = new Run();
                Text txt = new Text(line);
                run.Append(txt);
                p.Append(run);
                document.MainDocumentPart.Document.Body.GetFirstChild<SdtBlock>().Append(p);

            }