前端
const xhr = new XMLHttpRequest() const fileName = '小题分表.xls' xhr.open('post', '@Url.Action("ExportData")', true) xhr.responseType = 'blob' //xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8') let self = this; let data = { columns: self.columns, students: self.data, title: "小题分表" } var param = JSON.stringify(data); let ss = new FormData(); ss.append('data', param); xhr.send(ss) xhr.onload = function () { debugger const type = xhr.getResponseHeader('Content-Type') const blob = new Blob([this.response], { type: type }) if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob(blob, fileName) } else { const URL = window.URL || window.webkitURL const objectUrl = URL.createObjectURL(blob) if (fileName) { var a = document.createElement('a') // safari doesn't support this yet if (typeof a.download === 'undefined') { window.location = objectUrl } else { a.href = objectUrl a.download = fileName document.body.appendChild(a) a.click() a.remove() } } else { window.location = objectUrl } } }
后端
[AllowAction] [HttpPost] public FileResult ExportData(string data) { var dataString = data.ToString(); var paras = new { Title="", Columns = EmptyArr<string>(), Students = EmptyArr<Dictionary<string, string>>() }; paras = JsonConvert.DeserializeAnonymousType(dataString, paras); var dt = new DataTable(); foreach (string item in paras.Columns) { dt.Columns.Add(item); } foreach (Dictionary<string, string> item in paras.Students) { var row = dt.NewRow(); foreach (var key in item.Keys) { row[key] = item[key]; } dt.Rows.Add(row); } var stream = dt.SaveToMemoryStream(paras.Title); return File(stream, "application/ms-excel", "成绩单.xls"); }
public static T[] EmptyArr<T>() { return EmptyArray<T>.Value; } internal static class EmptyArray<T> { public static readonly T[] Value = new T[0]; }
快捷翻译 - 快到离谱! 划词翻译 自动发声 自动添加生词本 快捷翻译 - 快到离谱! 划词翻译 自动发声 自动添加生词本 快捷翻译 - 快到离谱! 划词翻译 自动发声 自动添加生词本 标签:MVC4,const,xhr,paras,传输数据,window,var,new,POST From: https://www.cnblogs.com/y5s78/p/17285367.html