1

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.

3
  • Duplicate Question.... : stackoverflow.com/questions/2800563/… Commented May 11, 2012 at 8:03
  • @Parminder in here the excel spreadsheet is an existing one or you are creating a new one. If you are creating a new sheet you can also use NPOI Commented May 11, 2012 at 8:07
  • @Vinay I want the sheet to be created dynamically. Commented May 11, 2012 at 8:09

2 Answers 2

6

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a .csv file. This is quick and easy, and makes it possible to open it in excel.

This post relates to yours:

Convert DataTable to CSV stream

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.