将图表导出到ASP.NET MVC5中的Excel

我试图导出数据和图表从我的ASP.net projet到Excel,我使用下面的代码,但我不能成功显示Excel文件中的图表,我只看到文本

public ActionResult ExportToExcel() { string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/Content/" + tmpChartName); Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;"); StringWriter stringWrite = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); string headerTable = @"<Table><tr><td>Begin</td><td><img src='" + imgPath2 + @"' /></td><td>end</td></tr></Table>"; Response.Output.Write(headerTable); Response.End(); return null; } 

一般来说,我们不需要矫枉过正的/高脂肪的库,而是致命的简单库/辅助类解决我们的问题

我发现一个助手类, 从这里生成Excel 2007+文件,并添加了一些扩展方法转换List数据到DataTable。

虽然它的文件有,但是需要总结一下:

  • 取消注释与MVC / ASP.net项目一起使用的第一行。
  • 该类在#region HELPER_FUNCTIONS有一个方法

     public static DataTable ListToDataTable<T>(List<T> list) 

但我使用另一个解决scheme,这是一个从Internet ToDataTable被盗取的扩展方法

 public static DataTable ToDataTable<T>(this List<T> list) // ExtensionMethods.cs static public class ExtensionMethods { public static DataSet ToDataSet<T>(this IEnumerable<T> data) { DataSet ds = new DataSet(); ds.Tables.Add(data.ToDataTable()); return ds; } public static DataTable ToDataTable<T>(this List<T> list) { DataTable dt = new DataTable(); foreach (PropertyInfo info in typeof(T).GetProperties()) { dt.Columns.Add(new DataColumn(info.Name, GetNullableType(info.PropertyType))); } foreach (T t in list) { DataRow row = dt.NewRow(); foreach (PropertyInfo info in typeof(T).GetProperties()) { if (!IsNullableType(info.PropertyType)) row[info.Name] = info.GetValue(t, null); else row[info.Name] = (info.GetValue(t, null) ?? DBNull.Value); } dt.Rows.Add(row); } return dt; } private static Type GetNullableType(Type t) { Type returnType = t; if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { returnType = Nullable.GetUnderlyingType(t); } return returnType; } private static bool IsNullableType(Type type) { return (type == typeof(string) || type.IsArray || (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))); } } 

最后使用简单的把这段代码放到Controller中

  public void ExportToExcel() { using (var db = new EFDbContext()) { var data = FetchDataAsList<MyDbEntityOrMvcModel>().ToDataTable(); CreateExcelFile.CreateExcelDocument(data, "report.xlsx", System.Web.HttpContext.Current.Response); } } 

请注意,我使用System.Web.HttpContext.Current.Response 而不是 HttpContext.Current.Response

并从视图中调用您的操作

 <a href="@Url.Action("GridExportToExcel", new { filter = Model.Filter})" class="fa fa-file-excel-o" />