在asp.net中创建Excel工作簿

use*_*076 3 c# asp.net vsto ms-office

我需要在点击按钮时为用户生成一个excel文件.我之前使用的是Netoffice,它在桌面应用程序中运行良好.但现在我想用asp.net应用程序做同样的事情.这样我的服务器代码就无法访问客户端的excel副本.我应该采取什么方法?

Tyl*_*eat 8

使用EPPlus.它允许您在服务器上创建Excel电子表格.我用过它并且效果很好.它支持高级功能.

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.Clear();
    Response.AddHeader("content-disposition", "attachment;  filename=file.xlsx");
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";                    
    Response.BinaryWrite(pck.GetAsByteArray());
    Response.End();
}
Run Code Online (Sandbox Code Playgroud)