使用C#填写Word docx中的文档变量 [英] Filling in a docvariable in Word docx using C#

查看:236
本文介绍了使用C#填写Word docx中的文档变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在VB 6中完成了一百次,但这使我无法使用C#2008和Word2007.我创建了一个带有两个docvariables的docx文件:

I've done this a hundred times in VB 6 but it's driving me nuts using C# 2008 and Word 2007. I created a docx file with two docvariables:

Some text here....

{docvariable replace1}
{docvariable replace2}

More text here......

我首先创建了一个宏,然后它起作用了:

I created a macro first to do it and it works:

Sub FillDocVariable()
'
' FillDocVariable Macro
'
'

  ActiveDocument.Variables("replace1").Value = "This is a test"
  ActiveDocument.Variables("replace2").Value = "it is only a test."
  ActiveDocument.Fields.Update

End Sub

这是我的C#代码(请注意,我正在学习中):

Here's my C# code (mind you I'm learning this as I go):

using Microsoft.Office.Interop.Word;
 object paramMissing = Type.Missing;
       object openfileName = @"C:\testing\Documents\1.docx";

      ApplicationClass WordApplication = new ApplicationClass();
      Document WordDocument = WordApplication.Documents.Open(ref openfileName, 
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing);

      WordDocument.Variables("replace1") = "This is a test";
      WordDocument.Variables("replace2").Value = "it's only a test!";
      WordDocument.Fields.Update;

这是我得到的错误:

错误1不可说成员 'Microsoft.Office.Interop.Word._Document.Variables' 不能像方法一样使用. 引用

Error 1 Non-invocable member 'Microsoft.Office.Interop.Word._Document.Variables' cannot be used like a method. Blockquote

推荐答案

如果您有兴趣,可以通过VS 2010和Word 2010如下:

If you're interested, the way to do this via VS 2010 & Word 2010 is as follows:

Application app = new Application();
Document doc = word.Documents.Add(filepath);
doc.Variables["var_name"].Value = your_value_here;
doc.Fields.Update();
doc.Save();
doc.Close();
app.Quit();

这篇关于使用C#填写Word docx中的文档变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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