MVC中使用方式:
1.前端js调用受到限制,简单的方式有:window.location.href = url; 或者 window.open(url);访问控制器中的方法
2,后台使用代码:
//方式一 public ActionResult NewGenerate(bool wordDoc) { string rootFolderFile = System.Web.HttpContext.Current.Server.MapPath("~/Template/ReportTemplate.doc"); if (System.IO.File.Exists(rootFolderFile)) { Aspose.Words.Document doc = new Aspose.Words.Document(rootFolderFile); var builder = new Aspose.Words.DocumentBuilder(doc); if (builder.MoveToBookmark("Report_No")) { builder.Write("testing");//write 内容不能为null } //方式一 if (wordDoc) { //doc文档 string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc"; var docStream = new MemoryStream(); doc.Save(docStream, Aspose.Words.SaveFormat.Doc); return File(docStream.ToArray(), "application/msword", fileName); } else { //pdf文档 string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"; var docStream = new MemoryStream(); doc.Save(docStream, Aspose.Words.SaveFormat.Pdf); return File(docStream.ToArray(), "application/vnd.ms-pdf", fileName); } } }
//方式二 public ActionResult Generate(bool wordDoc) { string rootFolderFile = System.Web.HttpContext.Current.Server.MapPath("~/Template/ReportTemplate.doc"); if (System.IO.File.Exists(rootFolderFile)) { Aspose.Words.Document doc = new Aspose.Words.Document(rootFolderFile); var builder = new Aspose.Words.DocumentBuilder(doc); if (builder.MoveToBookmark("Report_No")) { builder.Write("testing");//write 内容不能为null } //doc文档 string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc"; if (wordDoc) Response.ContentType = "application/msword"; else { fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"; Response.ContentType = "application/vnd.ms-pdf"; } Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); Response.ContentEncoding = System.Text.Encoding.Unicode; using (var memoryStream = new MemoryStream()) { doc.Save(memoryStream, Aspose.Words.SaveFormat.Doc); memoryStream.WriteTo(Response.OutputStream); memoryStream.Close(); } Response.End(); } }
ASP.NET中使用方式:
public void Generate(bool wordDoc) { string rootFolderFile = System.Web.HttpContext.Current.Server.MapPath("~/Template/ReportTemplate.doc"); if (System.IO.File.Exists(rootFolderFile)) { Aspose.Words.Document doc = new Aspose.Words.Document(rootFolderFile); var builder = new Aspose.Words.DocumentBuilder(doc); if (builder.MoveToBookmark("Report_No")) { builder.Write("testing");//write 内容不能为null } //doc文档 string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc"; if (wordDoc) doc.Save(Response, fileName, Aspose.Words.ContentDisposition.Attachment, new Aspose.Words.Saving.OoxmlSaveOptions(Aspose.Words.SaveFormat.Docx)); else { fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"; doc.Save(Response, fileName, Aspose.Words.ContentDisposition.Attachment, new Aspose.Words.Saving.OoxmlSaveOptions(Aspose.Words.SaveFormat.Pdf)); } Response.End(); } }