命名空间:(记得引入ASPJPEGLib.dll)
usingAspose.Words;
1.创建word模版,使用MergeFeild绑定数据
新建一个Word文档,命名为Template.doc
打开Template.doc必须在菜单的"插入→文档部件→域”找到MergeField并输入相应的域名
2.新建cs使用数组提供数据源
- stringtempPath = Server.MapPath("~/Docs/Temp/Template.doc");
- stringoutputPath = Server.MapPath("~/Docs/Output/Template.doc");
- //载入模板
- var doc = new Document(tempPath);
- //提供数据源
- String[] fieldNames = new String[] {"UserName", "Gender", "BirthDay", "Address"};
- Object[] fieldValues = new Object[] {"张三", "男", "1988-09-02", "陕西咸阳"};
- //合并模版,相当于页面的渲染
- doc.MailMerge.Execute(fieldNames, fieldValues);
- //保存合并后的文档
- doc.Save(outputPath);
- //在WebForm中,保存文档到流中,使用Response.?BinaryWrite输出该文件
- vardocStream = newMemoryStream();
- doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
- Response.ContentType = "application/msword";
- Response.AddHeader("content-disposition", "attachment; filename=Template.doc");
- Response.BinaryWrite(docStream.ToArray());
- Response.End();
- //在MVC中采用,保存文档到流中,使用base.File输出该文件
- vardocStream = newMemoryStream();
- doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
- returnbase.File(docStream.ToArray(), "application/msword","Template.doc");