OfficeDev / Open-Xml-PowerTools

MIT License
692 stars 26 forks source link

TextReplacer.SearchAndReplace cannot work on new WordprocessingDocument #267

Closed dkddkk closed 5 years ago

dkddkk commented 5 years ago

using (WordprocessingDocument xxDoc = WordprocessingDocument.Create(dstPath, WordprocessingDocumentType.Document)) { MainDocumentPart objMainDocumentPart = xxDoc.AddMainDocumentPart(); objMainDocumentPart.Document = new Document(new Body());

           //add paragraphs here

           TextReplacer.SearchAndReplace(xxDoc, tTarget, tKeyVP.Value, true);

}

SearchAndReplace will throw an exception. _exceptionMethod = {System.Xml.Linq.XDocument GetXDocument(DocumentFormat.OpenXml.Packaging.OpenXmlPart)}

It should be xxDoc cannot build the OpenXmlPart, what should I do? Please give me a method.

ps: for example: var inputDoc = WordprocessingDocument.Create("ttt.docx", WordprocessingDocumentType.Document);

        MainDocumentPart inputMainPart = inputDoc.AddMainDocumentPart();
        inputMainPart.Document = new Document(new Body(new 
       DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(new Text("Hello,world."))), new                       DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(new Text("xxxx.")))));
        inputDoc.Save();

        TextReplacer.SearchAndReplace(inputDoc, "xxx", "ccc", false);

I got a null exception, whenever I save it then open the doc or I create it in memory like above.

Please tell me what should I do?

The word is here: <?xml version="1.0" encoding="utf-8"?>Hello,world.</w:t></w:r></w:p>xxxx.</w:t></w:r></w:p></w:body></w:document>

ahmet269 commented 5 years ago

i suggest before you call search and replace , put a break point and check if your inputDoc has MainDocumentPart or not? you dont want this to be null before you calling textreplacer. and what is it that you are trying to achieve here?

tomjebo commented 5 years ago

Closing all issues as this repo is being archived and will no longer be maintained by Microsoft. The project is licensed for continued use and development by forking to your own repo.