I have Already Got my data pulled from Datatable & Dataset into Excel Sheet using Export Excel Cocept ,for each datatable and Dataset i am getting a Excel Sheet Ready. Is there any way that i can get all the sheets in a single Excel WorkBook using (c#)
protected void UploadDataTableToExcel(DataTable dtEmp, string filename)
{
string attachment = "attachment; filename=" + filename;
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = string.Empty;
foreach (DataColumn dtcol in dtEmp.Columns)
{
Response.Write(tab + dtcol.ColumnName);
tab = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dtEmp.Rows)
{
tab = "";
for (int j = 0; j < dtEmp.Columns.Count; j++)
{
Response.Write(tab + Convert.ToString(dr[j]));
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
protected void lnkExport_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string funcName = (string)ViewState["Reports"];
if (funcName == "DataTable1")
dt = DbAccess.GetDataTable1();
else if (funcName == "DataTable2")
dt = DbAccess.GetDataTable2();
if (ds.Tables.Count > 0)
{
string strFilename = funcName + ".xls";
UploadDataSetToExcel(ds, strFilename);
}
else
{
string strFilenames = funcName + ".xls";
UploadDataTableToExcel(dt, strFilenames);
}
You can use the Office.Excel interop to move the sheets to a single workbook after creating them and saving the workbook. This opens two workbooks and copy one sheet from the first workbook into the second one then save the second workbook:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace MergeBooks
{
class Program
{
static void Main(string[] args)
{
Excel.Application exApp = new Excel.Application();
Excel.Workbook wb1 = exApp.Workbooks.Open(@"C:\wb1.xls");
Excel.Workbook wb2 = exApp.Workbooks.Open(@"C:\wb2.xls");
Excel.Worksheet worksheet1 = wb1.Worksheets[1];
Excel.Worksheet worksheet2 = wb2.Worksheets[1];
worksheet1.Copy(worksheet2);
wb2.SaveAs(@"C:\wb3.xls");
wb1.Close(false);
wb2.Close(false);
exApp.Quit();
}
}
}
Read more about move and the interop: