如何从模板以编程方式创建 Word 文档 [英] How to create word docs programmatically from a template

查看:29
本文介绍了如何从模板以编程方式创建 Word 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Microsoft Office Word 中创建大约 600 个报告.这些文档填充有来自数据库的数据和在本地驱动器上找到的图像.我已经想通了,我可以在 Visual Studio 2010 中创建一个 Word 模板项目,并对该模板进行编程,这样当您输入单个值(id-number)时,它会自动填写整个文档.

I am trying to create about 600 reports in Microsoft office Word. The documents are populated with data from a database, and images found on a local drive. I have figured out, that I might create a Word Template project in visual studio 2010, and program the template, so that when you enter a single value (id-number), it automatically fills out the entire document.

我非常有信心这是可能的.唯一的问题是.如何遍历数据库中的所有条目,根据模板打开一个新文档并设置 id 值?

I am quite confident that this is possible. the only problem is. How do I loop through all entries in the database, open a new document based on the template and set the id-value?

for(int i = 0; i < idnumbers.Count(); i++)
{
     Word.Application app = new Word.Application();
     Word.Document doc = app.Documents.Add(@"C:..WordGeneratorinDebugWordTemplate.dotx");
     //input the id-number below: HOW??

     doc.SaveAs(FileName: @"c:	emp	est.docx"); 
}

该应用程序应该只运行一次,生成报告,它不必很快.它必须易于开发.

The application is supposed to run only once, generating the reports, and it doesn´t have to be fast. It just has to be easy to develop.

这里的问题是,似乎在 Word 项目之外无法访问 DocumentBase 对象.替代品 Microsoft.Office.Interop.Word.Document 没有像 SelectContentControlsByTitle 这样的功能,它允许我查找和设置我的 ContentControls.而这正是我需要做的..

The problem here is, that it seems that the DocumentBase object is not accessible outside the Word project. The substitute Microsoft.Office.Interop.Word.Document does not have functionality like SelectContentControlsByTitle that allows me to find and set my ContentControls. And that is exactly what I need to do..

这是我的代码现在将文本插入我的字段的样子:

This is what my code looks like now to insert the text into my field:

Word.Application app = new Word.Application();

Word.Document doc = app.Documents.Add(@"C:..	est.dotx");

foreach (Word.ContentControl cc in doc.SelectContentControlsByTitle("MyCCTitle"))
{
    cc.Range.Text += "1234";
}

doc.SaveAs(FileName: @"c:	emp	est.docx");

然后我在 BeforeSave 上的模板上的事件处理程序根据 MyCCTitle-titled 对象中的文本填写文档.

Then an eventhandler on my template on BeforeSave fills out the document based on the text in MyCCTitle-titled object.

推荐答案

也许您应该看看 Microsoft.Office.Tools.Word.Document?

Maybe you should be looking at Microsoft.Office.Tools.Word.Document?

Document.SelectContentControlsByTitle

这篇关于如何从模板以编程方式创建 Word 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆