我试图使用CSVHelper生成CSV文件并将其发送回浏览器,因此用户可以选择保存位置和文件名并保存数据。
该网站是基于MVC的。这里是我用来进行调用的jQuery按钮代码(数据是DTO列表的一些序列化的Json表示):
$.ajax({ type: "POST",url: unity.baseUrl + "common/ExportPayments",data: data });
这是控制器代码:
[HttpPost] public FileStreamResult ExportPayments() { MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); CsvWriter writer = new CsvWriter(sw); List<Payment_dto> pd = _commonService.GetPayments(); foreach (var record in pd) { writer.WriteRecord(record); } sw.Flush(); return new FileStreamResult(ms,"text/csv"); }
这似乎完全没有实现 – 将方法步骤调用到正确的代码位置,但响应为空,更不用说为用户提供文件对话框来保存数据。我已经通过了这个代码,并且从服务中返回数据,写入它,并且不会发生错误。那我做错了什么?
编辑:返回这个…
return File(ms.GetBuffer(),"text/csv","export.csv");
解决方法
请尝试以下代码:
public FileStreamResult ExportPayments() { var result = WriteCsvToMemory(_commonService.GetPayments()()); var memoryStream = new MemoryStream(result); return new FileStreamResult(memoryStream,"text/csv") { FileDownloadName = "export.csv" }; } public byte[] WriteCsvToMemory(IEnumerable<Payment_dto> records) { using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream)) using (var csvWriter = new CsvWriter(streamWriter)) { csvWriter.WriteRecords(records); streamWriter.Flush(); return memoryStream.ToArray(); } }
更新
以下是将复杂类型模型传递给使用GET HTTP方法的动作方法。我不喜欢这种方法,它只是给你一个想法,有一种方法来实现这一点。
模型
public class Data { public int Id { get; set; } public string Value { get; set; } public static string Serialize(Data data) { var serializer = new JavaScriptSerializer(); return serializer.Serialize(data); } public static Data Deserialize(string data) { var serializer = new JavaScriptSerializer(); return serializer.Deserialize<Data>(data); } }
行动:
[HttpGet] public FileStreamResult ExportPayments(string model) { //Deserialize model here var result = WriteCsvToMemory(GetPayments()); var memoryStream = new MemoryStream(result); return new FileStreamResult(memoryStream,"text/csv") { FileDownloadName = "export.csv" }; }
视图:
@{ var data = new Data() { Id = 1,Value = "This is test" }; } @Html.ActionLink("Export","ExportPayments",new { model = Data.Serialize(data) })