Try this way using Excel 9.0 Obejct libary
try
try
{
SqlConnection conn = new SqlConnection("Integrated Security=yes;Initial Catalog=Emp;Data Source=(local)");
conn.Open();
SqlCommand command = new SqlCommand("select * from emp", conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
Excel.ApplicationClass excel = new ApplicationClass();
excel.Application.Workbooks.Add(true);
System.Data.DataTable table = dataset.Tables[0];
int ColumnIndex=0;
foreach( System.Data.DataColumn col in table.Columns)
{
ColumnIndex++;
excel.Cells[1,ColumnIndex]=col.ColumnName; } int rowIndex=0;
foreach(DataRow row in table.Rows)
{
rowIndex++;
ColumnIndex=0; foreach(DataColumn col in table.Columns)
{
ColumnIndex++;
excel.Cells[rowIndex+1,ColumnIndex]=row[col.ColumnName];
}
}
excel.Visible = true;
Worksheet worksheet = (Worksheet)excel.ActiveSheet;
worksheet.Activate();
}
catch (XmlException exml)
{
// catch an xmlexception errors
MessageBox.Show( exml.Message);
}
|