ASP.NET MVC 拓展ViewResult实现word文档下载

?

最近项目中有同事用到word文档导出功能,遇到了一些导出失败问题,帮其看了下解决问题的同事,看了下之前的代码发现几个问题:

  1. 代码编写不规范,word导出功能未收口
  2. 重复代码导出都是
  3. 实现逻辑比较复杂,不易于维护及使用

在帮其解决问题后,写了下面这个ViewResult拓展,依赖Razor视图,能够直接转换页面为word文档,但是不支持外联样式表,样式可以定义在<head>头部

废话不多说,直接上代码:


?

public
class
WordFileResult : ViewResultBase

{

public
string FileName { get; set; }

?

public WordFileResult(object model, string viewName, string fileName)

{

ViewData = new
ViewDataDictionary(model);

ViewName = viewName;

FileName = fileName;

}

?

public WordFileResult() : this(new
ViewDataDictionary(), null, null)

{

?

}

?

public WordFileResult(string fileName) : this(new
ViewDataDictionary(), null, fileName)

{

?

}

?

public WordFileResult(object model) : this(model, null, null)

{

?

}

?

public WordFileResult(object model, string fileName) : this(model, null, fileName)

{

?

}

?

protected
override
ViewEngineResult FindView(ControllerContext context)

{

context.HttpContext.Response.Charset = "utf-8";

context.HttpContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

if (string.IsNullOrWhiteSpace(FileName))

{

FileName = ViewName;

}

context.HttpContext.Response.AppendHeader("Content-Disposition", string.Format("filename={0}.doc", FileName));

context.HttpContext.Response.ContentType = "application/msword";

ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, string.Empty);

if (result.View != null)

{

return result;

}

return
null;

}

}

?

?

public
static
class
ControllerExtensions

{

public
static
WordFileResult Word(this
Controller controller, object model)

{

return
new
WordFileResult(model);

}

?

public
static
WordFileResult Word(this
Controller controller, object model, string fileName)

{

return
new
WordFileResult(model, fileName);

}

?

public
static
WordFileResult Word(this
Controller controller, string fileName)

{

return
new
WordFileResult(fileName);

}

?

public
static
WordFileResult Word(this
Controller controller, object model, string viewName, string fileName)

{

return
new
WordFileResult(model, viewName, fileName);

}

?

?

}

?

使用方式比较简单:

  1. 定义视图,使用Razor视图布局word内容,

@using RazorWord.Models

@model List<LoginViewModel>

@{

Layout = null;

}

?

<!DOCTYPE html>

?

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>Export</title>

<style type="text/css">

.table td,

.table th {

background-color: #fff !important;

}

?

.table {

border-collapse: collapse !important;

background-color: #ffffff;

width: 100%;

margin-bottom: 20px;

}

?

.table thead > tr > th,

.table tbody > tr > th,

.table tfoot > tr > th,

.table thead > tr > td,

.table tbody > tr > td,

.table tfoot > tr > td {

padding: 8px;

line-height: 1.428571429;

vertical-align: top;

border-top: 1px solid #dddddd;

}

?

.table thead > tr > th {

vertical-align: bottom;

border-bottom: 2px solid #dddddd;

}

</style>

</head>

<body>

<div>

<table class="table">

<tr>

<th>电子邮件</th>

<th>密码</th>

<th>是否记住密码</th>

</tr>

@foreach (LoginViewModel item in Model)

{

<tr>

<td>@item.Email</td>

<td>@item.Password]</td>

<td>@(item.RememberMe ? "Y" : "N")</td>

</tr>

}

</table>

</div>

</body>

</html>

?

  1. 添加Action修改对应的Action方法返回值

?

public
ActionResult Export()

{

List<LoginViewModel> models = new
List<LoginViewModel>();

for (int i = 0; i < 20; i++)

{

models.Add(new
LoginViewModel()

{

Email = $"{i}[email protected]",

Password = new
Random().Next(1, 10000).ToString(),

RememberMe = i % 2 == 0 ? true : false

});

}

?

return
new
WordFileResult(models, "下载文件名称");

}

?

public
ActionResult Export1()

{

List<LoginViewModel> models = new
List<LoginViewModel>();

for (int i = 0; i < 20; i++)

{

models.Add(new
LoginViewModel()

{

Email = $"{i}[email protected]",

Password = new
Random().Next(1, 10000).ToString(),

RememberMe = i % 2 == 0 ? true : false

});

}

return
this.Word(models, "Export", "下载文件名称");

}

?

?

还有一种更方便的方式:使用ActionFilterAttribute过滤器

直接上代码:


public
class
WordDocumentAttribute : ActionFilterAttribute

{

public
string FileName { get; set; }

public
override
void OnResultExecuted(ResultExecutedContext filterContext)

{

var result = filterContext.Result as
ViewResult;

if (string.IsNullOrWhiteSpace(FileName))

{

FileName = result == null ? DateTime.Now.ToString("yyyy_MM_dd") : result.ViewName;

}

filterContext.HttpContext.Response.AppendHeader("Content-Disposition", string.Format("filename={0}.doc", FileName));

filterContext.HttpContext.Response.ContentType = "application/msword";

base.OnResultExecuted(filterContext);

}

}

使用方式:在一个Action方法上面添加特性:WordDocumentAttribute

?


?

[WordDocument(FileName = "下载文件名称")]

public
ActionResult Index()

{

return View();

}

?

?

搞定word导出功能,抛砖引玉,希望能够帮助到大家,也希望有更好实现方式的同学能够一起讨论!!!!!!

时间: 2024-08-06 11:58:01

ASP.NET MVC 拓展ViewResult实现word文档下载的相关文章

php将html转成word文档下载

<meta charset="utf-8" /> <?php class word{ function start(){ ob_start(); echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/

Asp.Net MVC WebApi2 自动生成帮助文档

WebAPI Help文档配置 开发环境VS2013+mvc5+WebApi2 一.通过NuGet引用Web API Test Client 安装后会多一个Areas文件夹 二.设置xml文档项目-->属性-->生成 三.在项目的App_Data文件夹下创建XmlDocument.xml 四.打开\Areas\HelpPage\App_Start\HelpPageConfig.cs文件,取消如下代码注释 运行项目,打开http://XXXX/Help,即可看到自动生成好的api文档

如何将PDF文件转换为能编辑的Word文档

近几年PDF文档越来越普遍化,原因就是word文档保存的文件有可能会因为电脑的差异而打不开,或者在显示上会有差异,给使用者造成不必要的麻烦.PDF能保存写作者想要的效果,将word文档储存为PDF是一个不错的选择.但是在需要编辑的时候又怎么把PDF文档转换成能编辑的word文档呢? 不是所有PDF文件都可以转换为能编辑的word文档,对于扫描的PDF文件只能转为图片内容的word文档,被加密的PDF文件如果不去除密码那么转换为word后也是图片内容. 方法A:要转换PDF文档的格式可以用在线的方

asp.net页面读取word文档内容显示

用asp.net实现对指定word文档内容的读取显示该如何实现?比如左边读取指定文件夹中所有的word文档,以文档的标题作为链接,点击文档标题则在右边某位置显示出该word文档中的内容(包括字体样式,图片显示等). 可以这样实现: 操作WORD配置说明 引入:Word的对象库文件“MSWORD.OLB”(word 2000为MSWORD9.OLB) 1.运行Dcomcnfg.exe 2.组件服务――计算机――我的电脑――DCOM配置――找到microsoft word 文档 3.点击属性 4.选

ASP.NET生成WORD文档,服务器部署注意事项

网上转的,留查备用,我服务器装的office2007所以修改的是Microsoft Office word97 - 2003 文档这一个. ASP.NET生成WORD文档服务器部署注意事项 1.Asp.net 2.0在配置Microsoft Excel.Microsoft Word应用程序权限时 error: 80070005 和8000401a 的解决总   2007-11-01 11:30  检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-00000

spring mvc 下 word 文档(含图片)导出

最近在处理 word 文档导出工作,整理并总结下. 经过一番百度和亲测,大部分人使用的都是iText,iReport等...当我去尝试用这几种方法的时候,要实现我的需求可以,但是代码量太大了~~~因为我的 word 文档结构比较复杂,内容较多,有点懒得去写.于是我寻求通过jsp 或 javascript 页面的方式导出,这样子格式都直接在web页面上已经编辑好了,不许通过代码再转成word的形式. javascript 方式的话需要使用到ActiveXObject,这样子对浏览器是有要求的~~直

asp.net如何实现word文档在线预览

原文:asp.net如何实现word文档在线预览 实现方式:office文档转html,再在浏览器里面在线浏览 1.首先引入com组件中office库,然后在程序集扩展中引入word的dll 2.将Microsoft.Office.Interop.Word的嵌入互操作类型设置为 false,如图 3.主要代码 C# 代码   复制 using System; using System.Collections.Generic; using System.Linq; using System.Web

ASP.Net控制不同的人编辑word文档中不同的可编辑区域

ASP.Net控制不同的人编辑word文档中不同的可编辑区域的完整示例 2010-10-15 11:43238人阅读评论(0)收藏举报 网页来源:http://blog.csdn.net/coco99/article/details/5942895 本文演示了如何使用C#在ASP.NET里调用Word限制用户只能编辑word文档中自己有权编辑的区域. 1.项目目的 演示使用不同的用户登录系统,打开同一个文件(不必同时打开),可以编辑的区域不一样,每个人都有属于自己的编辑区域. 2.解决思路 利用

asp.net生成word文档服务器配置

一.asp.net生成word文档,布署到正式的服务器上就出现           错误:System.Runtime.InteropServices.COMException (0x800A1098): 因为没有打开的文档,所以这一命令无效,就是thisApplication.Documents.Add的时候打不开或者创建不了word文档.            经过网络工程师交流后才把问题解决了.     解决方案:Windows Server 2008的安全性造成的,在Microsoft