将修改后的WordprocessingDocument保存到新文件中

Pau*_*aul 36 c# office-2007 openxml openxml-sdk

我正在尝试打开W​​ord文档,更改一些文本,然后将更改保存到新文档.我可以使用下面的代码完成第一项,但我无法弄清楚如何将更改保存到新文档(指定路径和文件名).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using DocumentFormat.OpenXml.Packaging;
using System.IO;

namespace WordTest
{
class Program
{
    static void Main(string[] args)
    {
        string template = @"c:\data\hello.docx";
        string documentText;

        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(template, true))
        {
            using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
            {
                documentText = reader.ReadToEnd();
            }


            documentText = documentText.Replace("##Name##", "Paul");
            documentText = documentText.Replace("##Make##", "Samsung");

            using (StreamWriter writer = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
                writer.Write(documentText);
            }
        }
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

我是一个完全的初学者,请原谅基本问题!

amu*_*rra 34

如果使用a MemoryStream,则可以将更改保存到新文件,如下所示:

byte[] byteArray = File.ReadAllBytes("c:\\data\\hello.docx");
using (MemoryStream stream = new MemoryStream())
{
    stream.Write(byteArray, 0, (int)byteArray.Length);
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
    {
       // Do work here
    }
    // Save the file with the new name
    File.WriteAllBytes("C:\\data\\newFileName.docx", stream.ToArray()); 
}
Run Code Online (Sandbox Code Playgroud)

  • 很好地改编了 https://docs.microsoft.com/en-us/previous-versions/office/office-12//ee945362(v=office.12) 上的内容。也可以使用 (FileStream fileStream = new FileStream("C:\\data\\newFileName.docx", System.IO.FileMode.CreateNew)) { stream.WriteTo(fileStream); }` 而不是 `File.WriteAllBytes( ... )` 如果只想获取字节,可以在 "wordDoc" `using` 块关闭后执行 `byteArray = stream.ToArray();`,在中间。 (2认同)

use*_*954 8

在Open XML SDK 2.5中:

    File.Copy(originalFilePath, modifiedFilePath);

    using (var wordprocessingDocument = WordprocessingDocument.Open(modifiedFilePath, isEditable: true))
    {
        // Do changes here...
    }
Run Code Online (Sandbox Code Playgroud)

wordprocessingDocument.AutoSave默认情况下为true,因此Close和Dispose将保存更改. wordprocessingDocument.Close不需要显式,因为using块会调用它.

这种方法不需要像接受的答案那样将整个文件内容加载到内存中.对于小文件来说这不是问题,但在我的情况下,我必须同时处理更多带有嵌入式xlsx和pdf内容的docx文件,因此内存使用率会非常高.


Moh*_*han 5

只需将源文件复制到目标并从那里进行更改。

File.copy(source,destination);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(destination, true))
    {
       \\Make changes to the document and save it.
       wordDoc.MainDocumentPart.Document.Save();
       wordDoc.Close();
    }
Run Code Online (Sandbox Code Playgroud)

希望这有效。

  • 1. 看起来你想写`wordDoc.Save()`。2. 没有 `Save()` 方法。所以这对我来说似乎不是一个有效的解决方案。有什么我想念的吗?? (2认同)