OpenXML: прочитать текстовый файл, добавить текст и открыть его без сохранения в веб-приложении ASP.Net - PullRequest
0 голосов
/ 28 июня 2018

Я пытаюсь прочитать файл шаблона с диска и добавить к нему абзац. После этого я хочу открыть это как новый файл. Шаблон не должен иметь изменений, сохраненных в нем. Я попробовал приведенный ниже код, и в результате шаблон изменяется с изменением, но файл, который открывается в браузере, не имеет этих изменений. Ясно, что я не получаю измененный поток в ответ. Как мне это сделать, а также избегать внесения изменений в файл шаблона.

public class DocumentCreator
    {
        public static void CreateDoc()
        {
            string strDoc = @"C:\Ash\foo.docx";
            string txt = "Bruno Rovani";

            using (Stream stream = File.Open(strDoc, FileMode.Open))
            {
                OpenAndAddToWordprocessingStream(stream, txt);
            }
        }

        public static void OpenAndAddToWordprocessingStream(Stream stream, string txt)
        {
            // Open a WordProcessingDocument based on a stream.
            using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, true))
            {
                // Assign a reference to the existing document body.
                Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                // Add new text.
                Paragraph para = body.AppendChild(new Paragraph());
                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text(txt));

                // HTTP response
                HttpResponse Response = HttpContext.Current.Response;
                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");

                //stream = wordprocessingDocument.MainDocumentPart.GetStream();
                stream.Position = 0;
                stream.CopyTo(Response.OutputStream);
                Response.Flush();
                Response.End();

            }
        }
    }

1 Ответ

0 голосов
/ 28 июня 2018

Решено

Добавлено wordprocessingDocument.MainDocumentPart.Document.Save();

PS: шаблон все еще изменяется. Не думайте, что есть способ избежать этого, но поскольку я буду заниматься поиском и заменой в реальном сценарии, для меня это не большая проблема.

так функция выглядит как

public static void OpenAndAddToWordprocessingStream(Stream stream, string txt)
        {
            // Open a WordProcessingDocument based on a stream.
            using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, true))
            {
                // Assign a reference to the existing document body.
                Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                // Add new text.
                Paragraph para = body.AppendChild(new Paragraph());
                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text(txt));
                **wordprocessingDocument.MainDocumentPart.Document.Save();**

                // HTTP response
                HttpResponse Response = HttpContext.Current.Response;
                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");

                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(Response.OutputStream);
                Response.Flush();
                Response.End();

            }
        }
...