Pau*_*aul 36 c# office-2007 openxml openxml-sdk
我正在尝试打开Word文档,更改一些文本,然后将更改保存到新文档.我可以使用下面的代码完成第一项,但我无法弄清楚如何将更改保存到新文档(指定路径和文件名).
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)
在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文件,因此内存使用率会非常高.
只需将源文件复制到目标并从那里进行更改。
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)
希望这有效。