Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用OpenXML修改Word文档不会';我不能在我的开发环境中工作_C#_Openxml - Fatal编程技术网

C# 使用OpenXML修改Word文档不会';我不能在我的开发环境中工作

C# 使用OpenXML修改Word文档不会';我不能在我的开发环境中工作,c#,openxml,C#,Openxml,在我正在进行的一个项目中,我们有一个非常特别的报告,它必须以Word文档的形式发布。昨天,我能够使用OpenXML让它在本地机器上工作。一切都很好,直到我将其提交到开发环境 在服务器上,我们在项目根目录下有一个内容目录(MyProject/content/),其中有一个模板文件template.dotx。下面是我们如何处理它: 控制器: [HasAccess] public FileContentResult SpecialReport([FromUri] string arg)

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

在服务器上,我们在项目根目录下有一个内容目录(
MyProject/content/
),其中有一个模板文件
template.dotx
。下面是我们如何处理它:

控制器:

    [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
    }
}
特别报告类:

    [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
    }
}
使用系统;
使用System.IO;
使用System.Collections.Generic;
使用System.Text.RegularExpressions;
使用DocumentFormat.OpenXml.Packaging;
名称空间MyWebProject.Web
{
公共类专用报告
{
#区域变量/属性
私有只读字符串_templatePath=string.Empty;
公共内存流报告流;
#endregion变量/属性
#区域构造函数
公共特殊报告(字符串模板路径)
{
_templatePath=templatePath;
}
#端域构造函数
#区域方法
公共void运行报告(IList模型)
{
ReportStream=newmemoryStream();
使用(fs=File.OpenRead(_templatePath))
{
财政司司长:CopyTo(ReportStream);;
Seek(0x00000000,SeekOrigin.Begin);
fs.Close();
}
使用(WordprocessingDocument pkgDoc=WordprocessingDocument.Open(ReportStream,true))
{
//设置文档的基本属性。。。
pkgDoc.PackageProperties.Creator=“我的Web应用”;
pkgDoc.PackageProperties.Created=DateTime.Now;
pkgDoc.PackageProperties.Title=“特别报告”;
pkgDoc.PackageProperties.ContentType=“应用程序/msword”;
//阅读全文,准备编辑。。。
字符串docText;
使用(StreamReader sr=newstreamreader(pkgDoc.MainDocumentPart.GetStream())
{
docText=sr.ReadToEnd();
高级关闭();
}
//替换收件人。
//资料来源:https://msdn.microsoft.com/en-us/library/office/bb508261.aspx
正则表达式recipientRegex=新正则表达式(“接收方”);
docText=recipientRegex.Replace(docText,模型[0].EmployeeDisplayName);
//通过替换将其他内容写入文档
//需要替换的特殊文本。
//将修改后的文档写入流。
使用(StreamWriter sw=newstreamwriter(pkgDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
sw.Close();
}
//关闭非托管资源!
pkgDoc.Close();
}
}
公共字节[]导出()
{
返回ReportStream.ToArray();
}
#端域法
}
}
我们的控制器方法派生了
SpecialReport
类的一个新实例,指向模板。然后,我们得到一组用于生成报告的模型,然后将模板复制到一个新的
MemoryStream
。我们在文档文本中查找特殊关键字(它们通常以奇怪的双V形开头),并根据需要替换它们。然后,我们将文档文本写回(克隆的!)内存流。之后,我们构建HTTP响应,并将其传递回客户端

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

实际上,在我们的开发环境中,没有生成替换。«Recipient»关键字未替换为第一个模型的属性(repository方法始终至少返回一个模型。)


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

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

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


现在,在观看《古墓丽影》(2001)中的忏悔之前,我会反复地把头撞在附近的一个立方体上。我觉得自己很笨。

两种情况下使用的模板文件是否相同?运行正则表达式的XML可能与您期望的不完全一样。例如,拼写检查器可以在XML中插入额外的元素,或者有时将单词拆分为多个单词。这足以破坏您的代码。模板文件将作为提交过程的一部分进行复制。我去核实了我的本地工作副本的文件;它检查出来了。我不认为这是问题所在(如果是的话,那会很好。)当你经历了苦修之后,你可以记住把这个标记为答案:因为我在回答我自己的问题,我要在原始帖子发布两天后才能这样做。但是,我会尽量不忘记的。否则,我有一种感觉,这条线将结束在每日WTF或什么。