c# - 使用 OpenXML 修改 Word 文档在我的开发环境中不起作用

标签 c# openxml

在我正在进行的一个项目中,我们有一份非常特殊的报告,绝对必须以 Word 文档的形式发布。昨天,我能够使用 OpenXML 让它在我的本地计算机上运行。一切都很好,直到我将其提交到开发环境。

在服务器上,我们在项目根目录 (MyProject/Content/) 之外有一个内容目录,其中包含一个模板文件 template.dotx。这是我们用它做的事情:

Controller :

    [HasAccess]
    public FileContentResult SpecialReport([FromUri] string arg)
    {
        // Prep Report...
        string templatePath = Server.MapPath(Url.Content("~/Content/Template.dotx"));
        var report = new SpecialReport(templatePath);

        // Fill out Report...
        var models = SomeRepository.GetSomeDataPoints(arg);
        report.RunReport(models);
        byte[] reportBytes = report.Export();

        // Prep Response...
        Response.ContentType = "application/msword";
        Response.AddHeader("content-disposition", "inline;filename=SpecialReport.doc");
        Response.Buffer = true;
        Response.Clear();
        Response.OutputStream.Write(reportBytes, 0, reportBytes.Length);
        Response.OutputStream.Flush();
        Response.End();

        return new FileContentResult(reportBytes, "application/msword");
    }

特别报告类:

using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml.Packaging;

namespace MyWebProject.Web
{
    public class SpecialReport
    {
        #region Variables / Properties

        private readonly string _templatePath = string.Empty;
        public MemoryStream ReportStream;

        #endregion Variables / Properties

        #region Constructor

        public SpecialReport(string templatePath)
        {
             _templatePath = templatePath;
        }

        #endregion Constructor

        #region Methods

        public void RunReport(IList<someModel> models)
        {
            ReportStream = new MemoryStream();

            using(fs = File.OpenRead(_templatePath))
            {
                fs.CopyTo(ReportStream);
                ReportStream.Seek(0x00000000, SeekOrigin.Begin);
                fs.Close();
            }

            using (WordprocessingDocument pkgDoc = WordprocessingDocument.Open(ReportStream, true))
            {
                // Set basic properties of the document...
                pkgDoc.PackageProperties.Creator = "My Web App";
                pkgDoc.PackageProperties.Created = DateTime.Now;
                pkgDoc.PackageProperties.Title = "Special Report";
                pkgDoc.PackageProperties.ContentType = "application/msword";

                // Read the full document text, in prep for editing...
                string docText;
                using (StreamReader sr = new StreamReader(pkgDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                    sr.Close();
                }

                // Replace the recipient.
                // Source: https://msdn.microsoft.com/en-us/library/office/bb508261.aspx
                Regex recipientRegex = new Regex("«Recipient»");
                docText = recipientRegex.Replace(docText, models[0].EmployeeDisplayName);

                // Write other things to the document by replacing
                // special text with what needs to be replaced.

                // Write the modified document to the stream.
                using (StreamWriter sw = new StreamWriter(pkgDoc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                    sw.Close();
                }

                // Close the unmanaged resource!
                pkgDoc.Close();
            }
        }

        public byte[] Export()
        {
            return ReportStream.ToArray();
        }

         #endregion Methods
    }
}

我们的 Controller 方法派生出一个指向模板的 SpecialReport 类的新实例。之后,我们得到一堆用于生成报告的模型,然后将模板复制到新的MemoryStream。我们在文档文本中查找特殊关键字(它们通常以那些奇怪的双 V 形符号开头),并根据需要替换它们。然后,我们将文档文本写回(克隆的!)内存流。然后,我们构建 HTTP 响应,并将其传递回客户端。

应该发生的是,用户在其前端执行某些操作,从而导致生成文档。生成的文档包含应使用的任何数据。当代码在本地运行时会发生这种情况。

实际发生的情况是,在我们的开发环境中,没有生成替代品。 «Recipient» 关键字不会被第一个模型中的属性替换(存储库方法始终返回至少一个模型。)

问题:鉴于上述代码,为什么当我在本地运行我的特别报告时,会生成一个替换了所有特殊关键字的 Word 文档,但是当我运行在我的开发环境中完全相同的代码,没有替换特殊关键字?

最佳答案

未生成 PDF 的原因是我需要提交 Controller 更改;事实证明,我实际上并没有在本地环境和开发环境之间使用相同的代码。

给大家的教训:Visual Studio 中的“排除的更改”列表?仔细注意它,确保里面没有需要推起来的东西。

现在,在观看古墓丽影(2001)之前,我要反复用头撞附近的立方体。我觉得真的很蠢。

关于c# - 使用 OpenXML 修改 Word 文档在我的开发环境中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31165411/

相关文章:

c# - Open XML - 如何向 docx 文档添加水印

c# - 使用await顺序调用异步任务有什么好处?

c# - FileIO.WriteAsync 挂起

c# - 使用反射查找具有自定义属性的方法

c# - 使用合并 (SimpleField) 字段从 .dotx 生成 .docx

c# - 如何将一些 VBA 代码嵌入到使用 ClosedXML 创建的电子表格中?

c# - 能否使用 CER 来保证永远不会调用 finalize?

c# - 如何执行真正耗时的方法? asp.net(定时)

java - OOXML 电子表格中的默认单元格类型

sql-server - 如何在 T-SQL 中从 XML 读取选项?