Save modified WordprocessingDocument to new file

前端 未结 5 667
礼貌的吻别
礼貌的吻别 2020-11-30 03:48

I\'m attempting to open a Word document, change some text and then save the changes to a new document. I can get the first bit done using the code below but I can\'t figure

5条回答
  •  情话喂你
    2020-11-30 04:10

    This approach allows you to buffer the "template" file without batching the whole thing into a byte[], perhaps allowing it to be less resource intensive.

    var templatePath = @"c:\data\hello.docx";
    var documentPath = @"c:\data\newFilename.docx";
    
    using (var template = File.OpenRead(templatePath))
    using (var documentStream = File.Open(documentPath, FileMode.OpenOrCreate))
    {
        template.CopyTo(documentStream);
    
        using (var document = WordprocessingDocument.Open(documentStream, true))
        {
            //do your work here
    
            document.MainDocumentPart.Document.Save();
        }
    }
    

提交回复
热议问题