Подтвердить что ты не робот

Сохранить измененный WordprocessingDocument в новый файл

Я пытаюсь открыть документ Word, изменить текст и сохранить изменения в новом документе. Я могу получить первый бит, сделанный с использованием кода ниже, но я не могу понять, как сохранить изменения в NEW документе (указав путь и имя файла).

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);
            }
        }
      }
    }
}

Я начинаю начинаю, поэтому простите основной вопрос!

4b9b3361

Ответ 1

Если вы используете 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()); 
}

Ответ 2

В Open XML SDK 2.5:

    File.Copy(originalFilePath, modifiedFilePath);

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

wordprocessingDocument.AutoSave истинно по умолчанию, поэтому Close и Dispose будут сохранять изменения. wordprocessingDocument.Close не требуется явно, потому что этот блок будет вызывать его.

Этот подход не требует загрузки всего содержимого файла в память, как в принятом ответе. Это не проблема для небольших файлов, но в моем случае мне приходится обрабатывать больше файлов docx со встроенным xlsx и pdf-содержимым одновременно, поэтому использование памяти будет довольно высоким.

Ответ 3

Просто скопируйте исходный файл в пункт назначения и внесите изменения.

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();
    }

Надеюсь, что это сработает.

Ответ 5

Для меня этот работал нормально:

// To search and replace content in a document part.
public static void SearchAndReplace(string document)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        string docText = null;
        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        Regex regexText = new Regex("Hello world!");
        docText = regexText.Replace(docText, "Hi Everyone!");

        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }
    }
}