簡體   English   中英

清除OpenXML word文檔內容或現有文本

[英]Clear OpenXML word Document content or existing text

我需要使用WordprocessingDocument創建新的OpenXMLDoc並向其中添加新的HTML內容。

到目前為止,我可以將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