【问题标题】:Export WebGrid data to Excel in MVC4在 MVC4 中将 WebGrid 数据导出到 Excel
【发布时间】:2015-03-30 12:36:37
【问题描述】:

我想将 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 asp.net-mvc-4 webgrid


    【解决方案1】:

    您实际上并未创建 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      相关资源
      最近更新 更多