【问题标题】:how to export .xlsx file C# ASP.NET MVC razor如何导出 .xlsx 文件 C# ASP.NET MVC 剃须刀
【发布时间】:2014-07-31 04:15:36
【问题描述】:

我想将数据导出到.xlsx 文件,但我似乎只能导出到.xls

导出.xlsx 文件的最简单方法是什么?

这是我用来导出到.xls 文件的代码:

GridView gv = new GridView();
gv.DataSource = listCatalogue.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Catalogue.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();

【问题讨论】:

    标签: c# asp.net asp.net-mvc excel razor


    【解决方案1】:

    您可以使用外部库,例如 EPPlus

    取自EPPlus documentation

     private void DumpExcel(DataTable tbl)
            {
                using (ExcelPackage pck = new ExcelPackage())
                {
                    //Create the worksheet
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
    
                    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                    ws.Cells["A1"].LoadFromDataTable(tbl, true);
    
                    //Format the header for column 1-3
                    using (ExcelRange rng = ws.Cells["A1:C1"])
                    {
                        rng.Style.Font.Bold = true;
                        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                        rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                        rng.Style.Font.Color.SetColor(Color.White);
                    }
    
                    //Example how to Format Column 1 as numeric 
                    using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
                    {
                        col.Style.Numberformat.Format = "#,##0.00";
                        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                    }
    
                    //Write it back to the client
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
                    Response.BinaryWrite(pck.GetAsByteArray());
                }
            }
    

    【讨论】:

    • 你能解释更多吗?
    • @user3894065 你能看一下epplus的文档吗?不然nsgocev的代码写的很好看懂#
    • @ChristianSauer 我在 OP 要求更多解释后添加了代码 :)
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多