使用MVC 5和WebAPI下载excel文件

这就是我正在使用的:AngularJS,BreezeJS在客户端。 对于服务器,我正在使用Web API和MVC 5。

我一直在寻找如何从服务器上构build和检索excel电子表格的方法,但是我不知所措。

我发现这个名为linqtocsv的插件可以极大地帮助我们构build出linq的csv文件。 codeproject的例子可以在这里find,nuget链接可以在这里find。

我也发现在stackoverstream的问题上很好的用法: Web API的HttpResponseMessage内容返回是不完整的

所以在执行上面的插件 – linq到csv之后,按照提到的stackover问题,似乎没有任何工作。

这里是我的服务器端代码(都直接从已经提到的链接):

[HttpPost] public HttpResponseMessage DistributorReport(JObject formValues) { try { var cqmo = formValues.ToObject<DistributorCQMO>(); var query = new FindDistributorsByLocationQuery { States = cqmo.States.Select(x => x.id), Cities = cqmo.Cities.Select(x => x.id), CitiesExclusion = cqmo.ExcludedCities.Select(x => x.id), ZipCodes = cqmo.ZipCodes.Select(x => x.id), ZipCodesExclusion = cqmo.ExcludedZipCodes.Select(x => x.id), ProductFamily = cqmo.ProductFamily.id, ProductSubFamilies = cqmo.ProductSubFamily.Select(x => x.id), MatchAllFilter = cqmo.MatchAllFilter, ClientTypeFilter = cqmo.ClientTypeFilter }; IEnumerable<DistributorDTO> distributors = this.queryProcessor.Process(query).AsQueryable(); CsvFileDescription outputFileDescription = new CsvFileDescription { SeparatorChar = '\t', // tab delimited FirstLineHasColumnNames = true }; HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new CsvContent<DistributorDTO>(outputFileDescription, "ObserverTripList.csv", distributors) }; return response; } catch (Exception ex) { // logger.ErrorException("Exception exporting as excel file: ", ex); return Request.CreateResponse(HttpStatusCode.InternalServerError); } } 

这里是助手类:

 public class CsvContent<T> : HttpContent { private readonly MemoryStream _stream = new MemoryStream(); public CsvContent(CsvFileDescription outputFileDescription, string filename, IEnumerable<T> data) { var cc = new CsvContext(); var writer = new StreamWriter(_stream); cc.Write(data, writer, outputFileDescription); writer.Flush(); _stream.Position = 0; Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); Headers.ContentDisposition.FileName = filename; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { return _stream.CopyToAsync(stream); } protected override bool TryComputeLength(out long length) { length = _stream.Length; return true; } } 

我尝试使用微风来使我的职位,它返回包装在微风对象的数据,如果挖掘到返回的对象,进入它的httpreponse属性,你会看到它的原始forms,选项卡分隔的数据,但是,内容应用程序在application / json中; charset = utf-8而不是excel格式。

编辑:

我有以下工作:

  $.ajax({ type: 'POST', url: 'MappingTool.API/api/Report/DistributorReport', data: JSON.stringify(jsonData), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (returnValue) { alert("success") // window.location = '/Reports/Download?file=' + returnValue; } }); 

我得到正确的答复,并能够查看所有的结果在提琴手和铬debugging器。 但是,如何让浏览器自动下载文件?

任何反馈意见是赞赏!

编辑:

这是我应该从MVC控制器或API控制器获取? 似乎有更多的支持MVC控制器,如可以在MVC中使用的FileResulttypes; 这会给我我的自动下载:“ 导出excel文件来查看mvc ”我已经看到它正在使用API​​控制器完成; 但是API控制器不是委托简单数据types而不是媒体内容的要点?