且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#visual studio 2010中的word文档生成报告

更新时间:2023-01-19 12:39:07

嗯......你可以使用'MS Word文档作为模板' - 文章如这个 C#:使用DocX以编程方式创建和处理Word文档 [ ^ ]很容易找到 - 谷歌'C#word文档模板' - 你也可以用PDF文档和iTextSharp做同样的事情......你给我们足够的信息,说明'文档'是多么复杂,所以我不能建议哪个更好。



我使用PDF和iTextSharp来生成一些非常复杂的报告,每个2页的2个'模板',我只是从磁盘读取它们 - 另一种方法是将模板嵌入为资源,在这种情况下,您将使用反射来读取它们。简而言之,您为System.Reflection添加使用,将模板文件添加到项目中并设置他们对嵌入资源和跟随代码的构建操作



well ... you can use 'a MS Word Document as a template' - articles like this C#: Create and Manipulate Word Documents Programmatically Using DocX[^] are pretty easy to find - google 'C# word document template' - you can also do the same with PDF documents and iTextSharp for instance ... you havnt given us enough info on how complex the 'document' is, so I cant suggest which is better.

I use PDF and iTextSharp to produce some very complex reports, there's 2 'templates' of 2 pages each, and I just read them from disk - the other approach would be to embed the 'templates' as a resource, in which case you would use reflection to read them .. in a nutshell, you add a 'using' for System.Reflection, add the template file(s) to the project and set the build action for them to 'Embedded Resource' and 'follow' the code

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
    string result = reader.ReadToEnd();
}





resourceName是程序集中嵌入的资源之一的名称。例如,如果您嵌入一个名为MyFile.txt的文本文件,该文件位于具有默认命名空间MyCompany.MyProduct的项目的根目录中,则resourceName为MyCompany.MyProduct.MyFile.txt



您还可以使用Assembly.GetManifestResourceNames()方法获取嵌入资源列表 - 我通常这样做,所以我可以在调试时转储资源的名称



(这个资源来自SO btw,我的代码不是'手')



resourceName is the name of one of the resources embedded in assembly. For example, if you embed a text file named "MyFile.txt" that is placed in the root of a project with default namespace "MyCompany.MyProduct", then resourceName is "MyCompany.MyProduct.MyFile.txt"

You can also use Assembly.GetManifestResourceNames() Method to get a list of embedded resources - I usually do this so I can dump the names of the resources while Im debugging

(this resource stuff is from SO btw, my code isnt 'to hand')