我用C#编写了Windows窗体程序。它包含文本框和数据网格。
我想将数据导出到Word文件中以使用模板。我在代码中添加了Microsoft Word库。
我还在Word文件中创建了文本框“ shapes”,并在其中放置了可以从我的c#程序中找到的文本
现在一切似乎都还不错,但是我被C#困住了,我可以替换普通文本,但是不能替换文本框“在word文件中”内的文本
这是我的代码:
private void FindAndReplace(Word.Application wordapp, object ToFindText, object replaceWithText)
{
object matchCase = true;
object matchWholeWord = true;
object matchWildCards = false;
object matchSoundLike = false;
object matchAllforms = false;
object forward = true;
object format = false;
object matchKashida = false;
object matchDiactitics = false;
object matchAlefHamza = false;
object matchControl = false;
object matchread_only = false;
object visible = true;
object replace = 2;
object wrap = 1;
wordapp.Selection.Find.Execute(ref ToFindText,
ref matchCase, ref matchWholeWord,
ref matchWildCards, ref matchSoundLike,
ref matchAllforms, ref forward,
ref wrap, ref format, ref replaceWithText,
ref replace, ref matchKashida,
ref matchDiactitics, ref matchAlefHamza,
ref matchControl);
}
private void CreateWordDocument(object filename, object SaveAs)
{
Word.Application wordApp = new Word.Application();
object missing = Missing.Value;
Word.Document myWordDoc = null;
if (File.Exists((string)filename))
{
object readOnly = false;
object isVisible = false;
wordApp.Visible = false;
myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
myWordDoc.Activate();
//find and replave
this.FindAndReplace(wordApp, "<date1>", textBox2.Text);
this.FindAndReplace(wordApp, "<date2>", textBox3.Text);
}
else
{
MessageBox.Show("File not found!");
}
//Svae as
myWordDoc.SaveAs2(ref SaveAs, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
myWordDoc.Close();
wordApp.Quit();
MessageBox.Show("File Created!");
}