简体   繁体   中英

Clear OpenXML word Document content or existing text

I need to create new OpenXMLDoc using WordprocessingDocument and addnew HTML Content to it.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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