Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c# - Create Excel workbook in asp.net

I need to generate an excel file for a user on the fl upon button click. I was using Netoffice before which worked fine for desktop applications. But now I want to do the same thing with an asp.net app. This way my server code doesn't have an access to the client's copy of excel. What approach should I take?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use EPPlus. It allows you to create Excel spreadsheets on the server. I've used it and it worked great. It supports advanced functions.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...