views:

89

answers:

1

hi, i have 3 datatables .i need to write these three datatable data in an excel sheet. as we know that under one excel sheet i can have (more than 1 sheet).

in a same way i need to write my 3 datatable data into one excel(where sheet1 will conatin dattable1,sheet2 will conatin dattable2,sheet3 will conatin dattable3)

this is the code i am using for write datatable data into grid then into excel

private void DataTableToExcel(DataTable dtResult)
        {
            try
            {
                DataGrid grid = new DataGrid();
                grid.HeaderStyle.Font.Bold = true;
                grid.DataSource = dtResult;
                grid.DataBind();
                // render the DataGrid control to a file
                using (StreamWriter sw = new StreamWriter(Server.MapPath("Report/Report.xls")))
                {
                    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                    {
                        grid.RenderControl(hw);
                    }
                }
                string filePath = Server.MapPath("~/" + "Report" + "/" + "Report.xls");
                System.IO.FileInfo targetFile = new System.IO.FileInfo(filePath);
                if (targetFile.Exists)
                {
                    Response.Clear();
                    string shortDate = DateTime.Now.ToShortDateString();
                    // Response.AddHeader("Content-Disposition", "attachment; filename=" + "Test");
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + "Emp" + shortDate + ".xls");
                    Response.AddHeader("Content-Length", targetFile.Length.ToString());
                    Response.ContentType = "application/vnd.ms-excel";
                    Response.WriteFile(targetFile.FullName);
                }
            }
            catch (Exception ex)
            {
                WriteLogError(ex.Message);
            }
        }

any help on this issue would be grealty appreciated. thanks.

A: 

You can achieve this using NPOI for C#. Really easy to use.

Take a look at these links:

Create Excel (.XLS and .XLSX) file from C#

Creating Excel spreadsheets .XLS and .XLSX in C#

You would refer to each sheet inside a workbook with:

 // Getting the worksheet by its name...
 HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");
Leniel Macaferi