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
124 views
in Technique[技术] by (71.8m points)

c# - Inserting data into an excel sheet from a DataTable

I'm extracting data from the database into a DataTable and displaying it by binding it to a Repeater control. Now I need to copy the same data into an excel spreadsheet. How can i use the same DataTable to the fill the spreadsheet. Please suggest.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I would suggest to create a real excel-file instead of a html table(what many people do). Therefor i can warmly recommend EPPlus(LGPL license).

Then it is simple. Assuming that you have a button BtnExportExcel:

protected void BtnExcelExport_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
    try {
        var pck = new OfficeOpenXml.ExcelPackage();
        var ws = pck.Workbook.Worksheets.Add("Name of the Worksheet");
        // get your DataTable
        var tbl = GetDataTable();
        ws.Cells["A1"].LoadFromDataTable(tbl, true, OfficeOpenXml.Table.TableStyles.Medium6);
        foreach (DataColumn col in tbl.Columns) {
            if (col.DataType == typeof(System.DateTime)) {
                var colNumber = col.Ordinal + 1;
                var range = ws.Cells[1, colNumber, tbl.Rows.Count, colNumber];
                // apply the correct date format, here for germany
                range.Style.Numberformat.Format = "dd.MM.yyyy";
            }
        }
        var dataRange = ws.Cells[ws.Dimension.Address.ToString()];
        dataRange.AutoFitColumns();

        Response.Clear();
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=NameOfExcelFile.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
    } catch (Exception ex) {
        // log exception
        throw;
    } 
    Response.End();
}

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

...