【问题标题】:Clear OpenXML word Document content or existing text清除 OpenXML word 文档内容或现有文本
【发布时间】:2018-07-18 12:56:25
【问题描述】:

我需要使用 WordprocessingDocument 创建新的 OpenXMLDoc 并向其中添加新的 HTML 内容。

到目前为止,我可以将 HTML 文本附加到现有文档,但我的要求是清除正文内容并将新的 HTML 内容添加到 word doc

string str = CKEditor1.Text;


            using (WordprocessingDocument doc = WordprocessingDocument.Open(Server.MapPath("~/Docs/Write.docx"), true))
            {
                string altChunkId = "myddId";
                MainDocumentPart mainDocPart = doc.MainDocumentPart;



                var run = new Run(new Text("test"));
                var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new ParagraphProperties(
                     new Justification() { Val = JustificationValues.Center }),
                                   run);


                doc.MainDocumentPart.Document.RemoveAllChildren<BookmarkStart>();
                doc.MainDocumentPart.Document.RemoveAllChildren<BookmarkEnd>();             
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body>" + str + "</body></html>"));
                AlternativeFormatImportPart formatImportPart =
                   mainDocPart.AddAlternativeFormatImportPart(
                      AlternativeFormatImportPartType.Html, altChunkId);

                formatImportPart.FeedData(ms);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainDocPart.Document.Body.Append(altChunk);
            }

【问题讨论】:

  • 您是否尝试过删除 Body 的所有后代,然后附加 HTML?

标签: c# ms-word openxml


【解决方案1】:

我们只需要添加下面一行,它就会清除Word Doc中的所有内容

mainDocPart.Document.Body.RemoveAllChildren();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多