Rajesh Akshith
Rajesh Akshith

Reputation: 321

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

Upvotes: 0

Views: 1188

Answers (1)

Rajesh Akshith
Rajesh Akshith

Reputation: 321

We Just need to add the below line it will clear all the contents in Word Doc

mainDocPart.Document.Body.RemoveAllChildren();

Upvotes: 1

Related Questions