我喜歡讓我的mvc 2應用程序生成MS Word和PDF格式的報告....目前正在使用Word。我發現這一點:ASP.NET MVC 2視圖(ViewModel) - > MS Word或PDF生成?
http://www.revium.com.au/articles/sandbox/aspnet-mvc-convert-view-to-word-document/
,我認爲基本上流從一個控制器動作到Word文檔輸出的觀點....
public ActionResult DetailedReport()
{
//[...]
return View();
}
public ActionResult DetailedReportWord()
{
string url = "DetailedReport";
return new WordActionResult(url, "detailed-report.doc");
}
而且繼承人延伸的ActionResult
類public class WordActionResult : ActionResult
{ private string Url { get; set;}
private string FileName { get; set;}
public WordActionResult(string url, string fileName)
{
Url = url;
FileName = fileName;
}
public override void ExecuteResult(ControllerContext context)
{
var curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + FileName);
curContext.Response.Charset = "";
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
curContext.Response.ContentType = "application/ms-word";
var wreq = (HttpWebRequest) WebRequest.Create(Url);
var wres = (HttpWebResponse) wreq.GetResponse();
var s = wres.GetResponseStream();
var sr = new StreamReader(s, Encoding.ASCII);
curContext.Response.Write(sr.ReadToEnd());
curContext.Response.End();
}
}
看起來像是pret TY不錯 - 但我的問題是,我的觀點從一個視圖模型渲染,這裏是行動
[HttpPost]
public ActionResult StartSearch(SearchResultsViewModel model)
{
SearchResultsViewModel resultsViewModel = _searchService.Search(model.Search, 1, PAGE_SIZE);
return View("Index", resultsViewModel);
}
,這裏是我的模型:
public class SearchResultsViewModel
{
[SearchWordLimit]
public string Search { get; set; }
public IEnumerable<Employee> Employees { get; private set; }
public IEnumerable<Organization> Organizations { get; private set; }
public PageInfo PageInfo { get; private set;}
public SearchResultsViewModel()
{
}
public SearchResultsViewModel(string searchString, IEnumerable<Employee> employees, IEnumerable<Organization> organizations, PageInfo pageInfo)
{
Search = searchString;
Employees = employees;
Organizations = organizations;
PageInfo = pageInfo;
}
}
我有麻煩還挺連接兩個 - 到使用我的viewmodel將視圖流化爲pdf
這是否真的生成Word文檔?它看起來只是用Word內容類型返回HTML。 – Rup 2010-06-07 18:40:24
@Rup,用戶得到一個很好的提示來打開它的話,保存在單詞中就好了。我使用這種技術擺脫不了解Office apis。 – jfar 2010-06-07 19:30:26