Public void exporttoexcel ()
{
String Path = request. physicalapplicationpath + "txtfile //" + getfilename () + ". xls ";
String SQL = session ["querystr"]. tostring ();
Dataset DS = maticsoft. dbutility. dbhelpersql. Query (SQL );
If (Ds. Tables. Count! = 0)
{
// Generate the complete path name of the. xls file
// String tempfilename = gettempfilename ();
Object filename = path;
Object nothing = system. reflection. Missing. value;
// Create an Excel file. The file name is generated in milliseconds.
Excel. Application myexcel = new excel. applicationclass ();
Myexcel. application. workbooks. Add (nothing );
Try
{
// Insert data in dataset into an Excel file
Int totalcount = 0;
For (int K = 0; k <Ds. Tables. Count; k ++)
{
Int ROW = Ds. Tables [K]. Rows. count;
Int column = Ds. Tables [K]. Columns. count;
For (INT I = 0; I <column; I ++)
{
Myexcel. cells [totalcount + 1, 1 + I] = convertcolumnname (Ds. Tables [K]. Columns [I]. columnname );
}
For (INT I = 0; I <row; I ++)
{
For (Int J = 0; j <column; j ++)
{
Myexcel. cells [totalcount + 2 + I, 1 + J] = "'" + getrowvalue (Ds. tables [K]. rows [I], DS. tables [K]. columns [J]. columnname );
}
}
Totalcount = totalcount + row + 4;
}
Try
{
Myexcel. activeworkbook. _ saveas (filename, nothing, xlsaveasaccessmode. xlexclusive, nothing );
}
Catch
{
Return;
}
// Make the generated Excel file visible
// Myexcel. Visible = true;
}
Catch (exception E)
{
}
Foreach (Excel. workbookclass W in myexcel. workbooks)
{
W. Close (false, nothing, nothing );
System. runtime. interopservices. Marshal. releasecomobject (w );
}
Myexcel. Quit ();
System. runtime. interopservices. Marshal. releasecomobject (myexcel );
Myexcel = NULL;
System. gc. Collect ();
Response. Clear ();
Response. Buffer = true;
Response. contenttype = "application/MS-excel ";
Response. appendheader ("content-disposition", "attachment?filename=todaydownlist.xls ");
System. Io. fileinfo = new fileinfo (PATH );
Response. addheader ("Content-Length", fileinfo. length. tostring ());
Response. writefile (PATH );
Response. End ();
}
Else
{
// System. Windows. Forms. MessageBox. Show ("no data ");
}
}
Note: The Excel namespace is in COM. Only Excel can be installed on the machine when the namespace is added.