简体   繁体   English

清除OpenXML word文档内容或现有文本

[英]Clear OpenXML word Document content or existing text

I need to create new OpenXMLDoc using WordprocessingDocument and addnew HTML Content to it. 我需要使用WordprocessingDocument创建新的OpenXMLDoc并向其中添加新的HTML内容。

As of now I can append the HTML Text to existing document but my requirement is to clear body contents and add new HTML content to word doc 到目前为止,我可以将HTML文本追加到现有文档中,但是我的要求是清除正文内容并将新的HTML内容添加到Word文档中

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);
            }

我们只需要添加以下行即可清除Word Doc中的所有内容

mainDocPart.Document.Body.RemoveAllChildren();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM