根据word模板(书签)创建导出word

假装没事ソ 提交于 2021-01-25 07:46:51
/// <summary>
/// 根据word模板(书签)创建word-导出
/// </summary>
/// <param name="context"></param>
public void export_Word(HttpContext context)
{
string templatePath = context.Server.MapPath("../../../模板.docx");//word模板位置
Document doc = new Document(templatePath);
//循环书签
foreach (Bookmark mark in doc.Range.Bookmarks)
{
if (mark != null)
{
switch (mark.Name)
{
case "UserName":
mark.Text = "饶哈哈";
break;
case "Sex":
mark.Text = "";
break;
case "Photo":
DocumentBuilder builder = new DocumentBuilder(doc);
string imgPath = context.Server.MapPath("/Admin/666.jpg");//图片地址
if (File.Exists(imgPath))
{
builder.MoveToBookmark("Photo");
builder.InsertImage(imgPath, Aspose.Words.Drawing.RelativeHorizontalPosition.Margin, 1, Aspose.Words.Drawing.RelativeVerticalPosition.Margin, 20, 100, 125, Aspose.Words.Drawing.WrapType.Square); //1:left、20:top、100:width、125:height
}
break;
default:
break;
}
}
}
string wordpath = context.Server.MapPath("/file/") + Guid.NewGuid() + ".docx";//word保存位置
doc.Save(wordpath, SaveFormat.Doc);

//以字符流的形式下载文件
FileStream fs = new FileStream(wordpath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
context.Response.ContentType = "application/vnd.ms-word;";
context.Response.Charset = "GB2312";
context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

//通知浏览器下载文件而不是打开;对中文名称进行编码
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("文件名", System.Text.Encoding.UTF8) + ".doc");
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!