在MVC4中将WebGrid数据导出到Excel

时间:2015-03-30 04:27:18

标签: excel asp.net-mvc-4 webgrid

我想通过格式化将WebGrid数据导出为ex​​cel。

我写了下面的代码,将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

时,它也会给我以下错误

enter image description here

1 个答案:

答案 0 :(得分:0)

您还没有真正创建过Excel文件。您已经创建了伪装成Excel 2003文件的HTML文件,这是一个坏主意。我解释了原因,并在my blog上介绍了一些替代方案。

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

string html = "<table style='color:red'><tr><td>Hello, world!</td></tr></table>";

但实际上,最好的办法是生成真正的Excel文件。这是我使用EPPlus的博客的快速摘录。它在Web窗体中显示。在MVC中,您实际上想要返回FileResult而不是直接写回应。

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();
}