本文将介绍如何使用spire.doc for java创建word邮件合并模板文档,以及合并文本值到模板。
import com.spire.doc.*;
import com.spire.doc.documents.paragraph;
import java.text.simpledateformat;
import java.util.date;
public class mailmerge {
public static void main(string[] args) throws exception {
string output = "output/mailmerge.docx";
//创建document实例
document document = new document();
//添加节
section section = document.addsection();
//添加三个段落
paragraph para = section.addparagraph();
paragraph para2 = section.addparagraph();
paragraph para3 = section.addparagraph();
//添加三个合并域
para.settext("联系人 : ");
para.appendfield("contact name", fieldtype.field_merge_field);
para2.settext("电话 : ");
para2.appendfield("phone", fieldtype.field_merge_field);
para3.settext("日期 : ");
para3.appendfield("date", fieldtype.field_merge_field);
//按合并域名称,设置合并域的文本值
date currenttime = new date();
simpledateformat formatter = new simpledateformat("yyyy-mm-dd hh:mm:ss");
string datestring = formatter.format(currenttime);
string[] filednames = new string[]{"contact name", "phone", "date"};
string[] filedvalues = new string[]{"李 生", " (86) 18812345678", datestring};
//合并文本到模板
document.getmailmerge().execute(filednames, filedvalues);
//保存文档
document.savetofile(output, fileformat.docx);
}
}
效果图: