日期:2009-04-29 浏览次数:20447 次
实现方法:首先需要引用VBA组建,我用的是office2003 Professional,Dll版本号为Microsoft word11.0,
另外当然还需要引用Interop.word.Dll.
代码如下:
#region 打开word文档,并且返回对象wDoc,wDoc
///
/// 打开word文档,并且返回对象wDoc,wDoc
///
/// 完整word文件路径+名称
/// 返回的word.Document wDoc对象
/// 返回的word.Application对象
public static void CreatewordDocument(string FileName,ref word.Document wDoc,ref word.Application WApp)
{
if(FileName == "") return;
word.Document thisDocument = null;
word.FormFields formFields = null;
word.Application thisApplication = new word.ApplicationClass();
thisApplication.Visible = true;
thisApplication.Caption = "";
thisApplication.Options.CheckSpellingAsYouType = false;
thisApplication.Options.CheckGrammarAsYouType = false;
Object filename = FileName;
Object ConfirmConversions = false;
Object ReadOnly = true;
Object AddToRecentFiles = false;
Object PasswordDocument = System.Type.Missing;
Object PasswordTemplate = System.Type.Missing;
Object Revert = System.Type.Missing;
Object WritePasswordDocument = System.Type.Missing;
Object WritePasswordTemplate = System.Type.Missing;
Object Format = System.Type.Missing;
Object Encoding = System.Type.Missing;
Object Visible = System.Type.Missing;
Object OpenAndRepair = System.Type.Missing;
Object DocumentDirection = System.Type.Missing;
Object NoEncodingDialog = System.Type.Missing;
Object XMLTransform = System.Type.Missing;
try
{
word.Document wordDoc =
thisApplication.Documents.Open(ref filename, ref ConfirmConversions,
ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
ref Revert,ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
ref NoEncodingDialog, ref XMLTransform );
thisDocument = wordDoc;
wDoc = wordDoc;
WApp = thisApplication;
formFields = wordDoc.FormFields;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
调用上面静态方法,打开目标文件并且把DataGrid中数据填充到对应word标签中去
#region word填充数据(For Example)
///
/// word填充数据
///
private void wordLoadData()
{
word.Document wDoc=null;
word.Application wApp=null;
sysFun.CreatewordDocument("E:\\监测报告(new).dot",ref wDoc,ref wApp);
//对标签"C"进行填充
object bkmC="C";
if(wApp.ActiveDocument.Bookmarks.Exists("C") == true)
&nbs