本文将介绍如何使用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);
}
}
效果图: