Excel文件不是通过AJAX调用从MVC下载的

时间:2019-06-26 12:19:16

标签: excel asp.net-mvc asp.net-ajax

我有一个简单的excel文件,该文件已从数据表导出到excel。但是我不确定为什么不下载该文件。我没有任何异常或错误。

从数据库中检索教师列表,并将其填充到数据表中。然后将数据表传递到Export Excel Function。

有什么我想念的吗?

操作结果

[HttpPost]
        public ActionResult GetTeachers(string firstname, string lastname)
        {
            try
            {
                List<GetTeachers_Result> returnResult = db.usp_GetTeachers(firstname, lastname).ToList();

                DataTable table = returnResult.FillDataTable<GetTeachers_Result>();
                byte[] bytes = Utilities.ExportExcel(table, "Teachers");
                return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Teachers.xlsx");
            }
            catch(Exception ex)
            {
            }

            return new EmptyResult();
        }

Utilities.cs

public static class Utilities
    {
        public static byte[] ExportExcel(DataTable dt, string worksheetName)
        {
            using (ExcelPackage pck = new ExcelPackage())
            {
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add(worksheetName);
                ws.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.Light1); //You can Use TableStyles property of your desire.    
                //for(int i=1; i< dt.Columns.Count; i++)
                //{
                //    if (dt.Columns[i].ColumnName.ToLower().Contains("date") || dt.Columns[i].ColumnName.ToLower().Contains("dte"))
                //        ws.Column(i).Style.Numberformat.Format = "mm/dd/yyyy h:mm";
                //}
                Byte[] fileBytes = pck.GetAsByteArray(); //Read the Excel file in a byte array    
                return fileBytes;
            }
        }

        public static DataTable FillDataTable<T>(this List<T> lstItems)
        {
            DataTable dt = new DataTable(typeof(T).Name);
            PropertyInfo[] props = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            foreach (PropertyInfo p in props)
            {
                if (p.PropertyType.Name != "DateTime")
                    dt.Columns.Add(p.Name.Replace("_", " "), Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType);
                else
                    dt.Columns.Add(p.Name.Replace("_", " "));
            }

            foreach (T item in lstItems)
            {
                var values = new object[props.Length];
                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }
                dt.Rows.Add(values);
            }
            return dt;
        }
    }

AJAX呼叫

$scope.excelExport = function(){
         var dataObject = JSON.stringify({
                'firstname': $('#txt-firstName').val().trim().toLowerCase(),
                'lastname': $('#txt-lastName').val().trim().toLowerCase(),
            });

            $.ajax({
                url: "/School/GetTeachers",
                type: 'POST',
                async: false,
                dataType: 'json',
                contentType: 'application/json',
                data: dataObject,
                success: function (data) { },
                error: function (xhr) { }
            });
}

0 个答案:

没有答案