gpt4 book ai didi

c# - 使用 C# 在 Word docx 中填充文档变量

转载 作者:太空狗 更新时间:2023-10-29 21:52:10 27 4
gpt4 key购买 nike

我已经在 VB 6 中完成了一百次,但使用 C# 2008 和 Word 2007 时它让我抓狂。我创建了一个包含两个文档变量的 docx 文件:

Some text here....

{docvariable replace1}
{docvariable replace2}

More text here......

我首先创建了一个宏来执行它并且它有效:

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# 代码(请注意,我边学边学):

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;

这是我得到的错误:

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

最佳答案

如果您有兴趣,通过 VS 2010 和 Word 2010 执行此操作的方法如下:

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# - 使用 C# 在 Word docx 中填充文档变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3647024/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com