我有一个用 c# 编写的 winForm 应用程序,并且我有一个包含目录中的文件的树视图。它还包含有关每个文件的数据(完整路径、创建时间、大小),如下所示:
我正在尝试将此数据导出到 MS-Word 模板,如下所示:
我的问题是复制每个文件的合并字段并将每个文件属性(文件数更改)插入到位,如下所示:
这是我的代码:
private void btnExportWord_Click_1(object sender, EventArgs e)
{
object oMissing = Missing.Value;
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();
oWord.Visible = false;
oWordDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
Object oTemplatePath = @"C:\test\MyXMLTemplate.dotx";
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
for (int i = 0; i < treeViewXMLFiles.Nodes[0].Nodes.Count; i++)
{
string strFilename = treeViewXMLFiles.Nodes[0].Nodes[i].Text;
string strFull_path = treeViewXMLFiles.Nodes[0].Nodes[i].Nodes[0].Text;
string strCreationTime = treeViewXMLFiles.Nodes[0].Nodes[i].Nodes[1].Text;
string strSize = treeViewXMLFiles.Nodes[0].Nodes[i].Nodes[2].Text;
foreach (Word.Field myMergeField in oWordDoc.Fields)
{
Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
fieldName = fieldName.Trim();
if (fieldName == "File_Name")
{
myMergeField.Select();
oWord.Selection.TypeText(strFilename);
}
if (fieldName == "Full_Path")
{
myMergeField.Select();
oWord.Selection.TypeText(strFull_path);
}
if (fieldName == "CreationTime")
{
myMergeField.Select();
oWord.Selection.TypeText(strCreationTime);
}
if (fieldName == "Size")
{
myMergeField.Select();
oWord.Selection.TypeText(strSize);
}
}
}
}
Object oSaveAsFile = (Object)@"C:\test\FINISHED_XML_Template.doc";
oWordDoc.SaveAs(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
oWordDoc.Close(false, ref oMissing, ref oMissing);
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
}
我想找很久没有成功的答案。
我希望这里的任何人都可以帮助我。