【发布时间】:2019-01-06 04:40:58
【问题描述】:
我正在使用 word 模板创建一个 word 文件,并从数据表中转储数据以导出多页文件,我尝试了许多 dll,但获得了版权,我想要一些免费的东西,我需要你的想法和示例 我在 Microsoft.Office.Interop.Word 库中有以下代码,但以下页面为空白
private void MailMerge(DataTable dt )
{
Object oMissing = System.Reflection.Missing.Value;
Object oTrue = true;
Object oFalse = false;
string filePath = Path.Combine(HttpContext.Current.Server.MapPath(@"~/ExportWord/MauSo04.dot"));
Object oTemplatePath = filePath;
Application wordApp = new Application();
Document wordDoc = new Document();
wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
wordApp.Visible = true;
for (int i = 0; i < dt.Rows.Count; i++)
{
string Name= dt.Rows[i]["Name"].ToString();
string Address= dt.Rows[i]["Address"].ToString();
foreach (Field myMergeField in wordDoc.Fields)
{
int iTotalFields = 0;
iTotalFields++;
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.Contains("Name"))
{
myMergeField.Select();
wordApp.Selection.TypeText(Name);
}else if (fieldName.Contains("Address"))
{
myMergeField.Select();
wordApp.Selection.TypeText(Address);
}
}
}
wordDoc.Words.Last.InsertBreak(WdBreakType.wdPageBreak);
}
var path = Path.Combine(HttpContext.Current.Server.MapPath(@"~/ExportWord/Test.doc"));
wordDoc.SaveAs(path);
wordDoc.Close();
wordApp.Application.Quit();
Marshal.FinalReleaseComObject(wordApp);
Marshal.FinalReleaseComObject(wordDoc);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
【问题讨论】: