DataTable dt = _db.Ado.GetDataTable("select * from pub_member where groupid<>3 and xld<>1 order by id asc");
string templatePath = FileHelper.absolutPath("wwwroot/mb/kh.docx"); //模板文件路径
//
var template = new Document(templatePath); //加载模板
// 创建合并文档
var combinedDocument = new Document();
combinedDocument.RemoveAllChildren();
// 生成多个副本并合并
for(int i=0;i<dt.Rows.Count;i++)
{
var tempDocument = template.Clone();
#region 替换占位符
var placeholders = new Dictionary<string, string>
{
{ "{xm}", "111" }
};
foreach (var placeholder in placeholders)
{
tempDocument.Range.Replace(placeholder.Key, placeholder.Value, new Aspose.Words.Replacing.FindReplaceOptions());
}
#endregion
// 合并到目标文档
combinedDocument.AppendDocument(tempDocument, ImportFormatMode.KeepSourceFormatting);
}
var stream = new MemoryStream();
combinedDocument.Save(stream, SaveFormat.Docx);
stream.Position = 0;
// 返回文件时不使用 using,避免释放 Stream
return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "1.docx");