你的位置:首页 > ASP.net教程

[ASP.net教程].net根据模板对Word用Aspose Word操作


命名空间:(记得引入ASPJPEGLib.dll)

usingAspose.Words;

1.创建word模版,使用MergeFeild绑定数据

新建一个Word文档,命名为Template.doc

 打开Template.doc必须在菜单的"插入→文档部件→域”找到MergeField并输入相应的域名

 

2.新建cs使用数组提供数据源

  1. stringtempPath = Server.MapPath("~/Docs/Temp/Template.doc");
  2. stringoutputPath = Server.MapPath("~/Docs/Output/Template.doc");
  3. //载入模板
  4. var doc = new Document(tempPath);
  5. //提供数据源
  6. String[] fieldNames = new String[] {"UserName", "Gender", "BirthDay", "Address"};
  7. Object[] fieldValues = new Object[] {"张三", "男", "1988-09-02", "陕西咸阳"};
  8. //合并模版,相当于页面的渲染
  9. doc.MailMerge.Execute(fieldNames, fieldValues);
  10. //保存合并后的文档
  11. doc.Save(outputPath);
  12. //在WebForm中,保存文档到流中,使用Response.?BinaryWrite输出该文件
  13. vardocStream = newMemoryStream();
  14. doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
  15. Response.ContentType = "application/msword";
  16. Response.AddHeader("content-disposition", "attachment; filename=Template.doc");
  17. Response.BinaryWrite(docStream.ToArray());
  18. Response.End();
  19. //在MVC中采用,保存文档到流中,使用base.File输出该文件
  20. vardocStream = newMemoryStream();
  21. doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
  22. returnbase.File(docStream.ToArray(), "application/msword","Template.doc");