将WebGrid数据导出到MVC4中的Excel

将WebGrid数据导出到MVC4中的Excel,excel,asp.net-mvc-4,webgrid,Excel,Asp.net Mvc 4,Webgrid,我想将WebGrid数据导出为excel格式 我写了下面的代码,将WebGrid数据导出到Excel WebGrid grid = new WebGrid(source: listReport, canPage: false, canSort: false); string gridData = grid.GetHtml( columns: grid.Columns( grid.Column("ID", "ID"

我想将WebGrid数据导出为excel格式

我写了下面的代码,将WebGrid数据导出到Excel

 WebGrid grid = new WebGrid(source: listReport, canPage: false, canSort: false);

        string gridData = grid.GetHtml(
            columns: grid.Columns(
                    grid.Column("ID", "ID"),
                    grid.Column("Name", "Name"),
                    grid.Column("Summary", "Summary"),
                    grid.Column("Detail", "Detail"),
                    grid.Column("ProjectName", "Project Name")
                    )
                ).ToString();


        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=CustomerInfo.xls");
        Response.ContentType = "application/excel";
        Response.Write(gridData);
        Response.End();
我想在excel中格式化。 是否可以导出具有格式的数据

当我打开生成的excel时,也会出现以下错误


您实际上还没有创建Excel文件。您创建了一个伪装成Excel2003文件的HTML文件,这是一个坏主意。我解释了原因,并介绍了一些备选方案

由于您创建源HTML的方式,样式设置将很困难。您可以使用库解析它,然后通过每个元素
style
属性添加基本样式。或者不使用WebGrid,您可以手动构建HTML

string html = "<table style='color:red'><tr><td>Hello, world!</td></tr></table>";
protected void ExportBtn_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=myexcelfile.xlsx");
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    var package = new ExcelPackage(); //create a new package, this is the equivalent of an XLSX file.
    var sheet = package.Workbook.Worksheets.Add("My Data"); //Add a new sheet to the workbook
    var dt = GetDataTable(); //This retrieves a System.Data.DataTable, you'd likely get it from your database.
    sheet.Cells["A1"].LoadFromDataTable(dt, true); //EPPlus contains helper function to load data from a DataTable, though you could manually fill in rows/column values yourself if you want
    var range = sheet.Cells[1, 1, dt.Rows.Count + 1, 2]; //We're getting a reference to all the cells that contain data
    var table = sheet.Tables.Add(range, "My Data Table"); //Creating an Excel table
    table.TableStyle = TableStyles.Medium8; //Setting the table style to something that looks nice
    range.AutoFitColumns(); //Auto fitting the column widths.
    Response.BinaryWrite(package.GetAsByteArray());
    Response.End();
}