Save modified WordprocessingDocument to new file

前端 未结 5 658
礼貌的吻别
礼貌的吻别 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:31

    In Open XML SDK 2.5:

        File.Copy(originalFilePath, modifiedFilePath);
    
        using (var wordprocessingDocument = WordprocessingDocument.Open(modifiedFilePath, isEditable: true))
        {
            // Do changes here...
        }
    

    wordprocessingDocument.AutoSave is true by default so Close and Dispose will save changes. wordprocessingDocument.Close is not needed explicitly because the using block will call it.

    This approach doesn't require entire file content to be loaded into memory like in accepted answer. It isn't a problem for small files, but in my case I have to process more docx files with embedded xlsx and pdf content at the same time so the memory usage would be quite high.

提交回复
热议问题