asp.net 导出word ktb 带图片
一、引用
using Aspose.Words; using Aspose.Words.Drawing; using Aspose.Words.Replacing;
二、标签替换
// 加载模板文件
string templatePath = Server.MapPath("ktb.docx");
Document doc = new Document(templatePath);
// 创建合并文档
var combinedDocument = new Document();
combinedDocument.RemoveAllChildren();
if (ds.Tables[0].Rows.Count > 0)
{
string zphmc = Util.GuanLian("zph", sxh, "title");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string id = ds.Tables[0].Rows[i]["qyid"].ToString();
#endregion
#region 替换占位符
var tempDocument = doc.Clone();
var placeholders = new Dictionary<string, string>
{
{"{展位号}", twh},
{"{公司名称}", qymc},
{"{招聘会}", zphmc},
{"{企业简介}", qyjj},
{"{联系电话}", lxr +""+lxsj},
{"{地址}", lxdz},
{"{邮箱网站}", emall},
{"{招聘岗位}", gw},
};
foreach (var placeholder in placeholders)
{
tempDocument.Range.Replace(placeholder.Key, placeholder.Value, new Aspose.Words.Replacing.FindReplaceOptions());
}
var options = new FindReplaceOptions();
options.ReplacingCallback = new ImageReplaceCallback(qcode);
tempDocument.Range.Replace(
new Regex(Regex.Escape("{二维码}")),
"",
options
);
#endregion
// 合并到目标文档
combinedDocument.AppendDocument(tempDocument, ImportFormatMode.KeepSourceFormatting);
}
}
ds.Clear();
ds.Dispose();
db.Dispose();
// 将文档保存到内存流中
MemoryStream stream = new MemoryStream();
combinedDocument.Save(stream, SaveFormat.Docx);
// 设置响应头以提示浏览器下载文件
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("Content-Disposition", "attachment; filename=Ktb.docx");
Response.BinaryWrite(stream.ToArray());
stream.Position = 0;
Response.End();三、图片替换类
public class ImageReplaceCallback : IReplacingCallback
{
private string imagePath;
public ImageReplaceCallback(string path)
{
imagePath = path;
}
public ReplaceAction Replacing(ReplacingArgs e)
{
DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
builder.MoveTo(e.MatchNode);
Shape shape = builder.InsertImage(imagePath);
shape.Width = 80;
shape.AspectRatioLocked = true;
shape.WrapType = WrapType.Inline;
// 关键:调整二维码所在段落的行距,防止图片上下被裁切
Paragraph para = shape.ParentNode as Paragraph;
if (para != null)
{
para.ParagraphFormat.LineSpacingRule = LineSpacingRule.AtLeast;
para.ParagraphFormat.LineSpacing = shape.Height + 2;
}
e.Replacement = "";
return ReplaceAction.Replace;
}
}
