Word2007使用MailMerge功能打印合同外挂程序



首先,准备一份word版的合同文件模板,同时通过MailMerge功能配置好数据源。(里面的相关信息是要通过MailMerge功能从数据源来显示的).

打开文档,选择‘邮件’-‘选择收件人’-‘从现有列表’,并拷贝出 配置好的数据源文件路径:

例如:D:\Users\administrator\My Documents\我的数据源\10.79.1.247_sqlserver2008.odc


Word2007使用MailMerge功能打印合同外挂程序_第1张图片
Word2007使用MailMerge功能打印合同外挂程序_第2张图片
 
 
在Visual Studio中新建一个windows form项目,并添加对Office.Word的引用

编写一个简单界面 如:


Word2007使用MailMerge功能打印合同外挂程序_第3张图片
然后要做的就是 

1.在Form1的load事件中用Word的API打开合同模板文档

2.并连接数据源

3.开启‘预览结果’

4.保护文档为不能编辑
5.控制翻页

6.调用打印

7.关闭文档

 

相关步骤的代码:

第1步.

object strFileName = @"e:\\还款协议.docx";
            String ds = "D:\\Users\\administrator\\My Documents\\我的数据源\\10.79.1.247_sqlserver2008.odc";
            
            wrdApp = new Microsoft.Office.Interop.Word.Application();
            wrdApp.Visible = true;

            // Open document.
            wrdDoc = wrdApp.Documents.Open(ref strFileName, ref oMissing, true, 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);

第2步.

wrdDoc.MailMerge.OpenDataSource(ds, 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);

 

第3步.

wrdDoc.MailMerge.ViewMailMergeFieldCodes = 0; //开启预览

 

第4步.

wrdDoc.Protect(WdProtectionType.wdAllowOnlyReading, Type.Missing, //文档不可编辑
                Type.Missing, Type.Missing, Type.Missing);

 第5步.

分别编写‘上一页’‘下一页’的click事件

private void button1_Click(object sender, EventArgs e)
        {
            wrdDoc.MailMerge.DataSource.ActiveRecord = WdMailMergeActiveRecord.wdNextRecord;
            recordIndex += 1;
            enableButtons();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            wrdDoc.MailMerge.DataSource.ActiveRecord = WdMailMergeActiveRecord.wdPreviousRecord;
            recordIndex -= 1;
            enableButtons();
        }

 第6步.

直接调用Document的printout方法,具体我没实现了

wrdDoc.PrintOut(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, 
                ref oMissing, ref oMissing, ref oMissing);

 

第7步.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            wrdDoc.Close(false, ref oMissing, ref oMissing);
            wrdApp.Quit(false, ref oMissing, ref oMissing);
            wrdApp = null;
        }

 

完成之后运行程序,会打开合同模板文档,文档为不可编辑状态,只能通过‘上一页’和‘下一页’可以在模板中插入不同人员信息,关闭程序后合同文档也会一起关闭

效果如下:
Word2007使用MailMerge功能打印合同外挂程序_第4张图片
 

 

你可能感兴趣的:(打印,C#,合同,mailmerge)