R
R
Roman Koff2016-02-11 16:45:02
C++ / C#
Roman Koff, 2016-02-11 16:45:02

How to create a .docx file from another .docx file using the Open XML SDK?

There is a DOCX file with a form. You need to make a copy of it, but at the same time make a replacement in the text of the form (replace Number with a number, and replace DateS with the current date).
I do it like this:

string fileSrc = Server.MapPath("/files/source_pko.docx");
string fileRes = Server.MapPath("/files/pko000.docx");
using (var docSrc = WordprocessingDocument.Open(fileSrc, false))
using (var docRes = WordprocessingDocument
  .Create(fileRes, WordprocessingDocumentType.Document))
{
  docRes.AddMainDocumentPart();
  var sb = new StringBuilder();
  using (var stream = new StreamReader(docSrc.MainDocumentPart.GetStream()))
    sb.Append(stream.ReadToEnd());
  var date = DateTime.Now;
  sb.Replace("Number", "123");
  sb.Replace("DateS", date.ToShortDateString());
  using (var stream = new StreamWriter(docRes.MainDocumentPart.GetStream(FileMode.Create)))
    stream.Write(sb);
}

At the same time, all content moves normally, but the styles of the document fly off. Maybe I'm doing something wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question