Method 1:
Void getdatatoexcel () // can be sent to the local and client
{
// Sqlconnection conn = new sqlconnection ("Server = 61.142.81.171; database = newqian; uid = sui2; Pwd = 09 * 01%"); // remote
Sqlconnection conn = new sqlconnection ("Server =.; database = newlandcnbackupserver; uid = sa; Pwd ="); // localhost
Sqldataadapter da = new sqldataadapter ("select top 10 * From luser", Conn );
Dataset DS = new dataset ();
Da. Fill (DS, "luser ");
Datatable dt = Ds. Tables ["luser"];
String filepath = @ "D: \ IIS \ userdata.xls ";
Filestream FS = new filestream (filepath, filemode. Create, fileaccess. Write );
Streamwriter Sw = new streamwriter (FS, system. Text. encoding. getencoding ("gb2312 "));
Sw. writeline ("userid \ tusername \ tuserrealname ");
Foreach (datarow DR in DT. Rows)
{
Sw. writeline (Dr ["userid"] + "\ t" + Dr ["username"] + "\ t" + Dr ["userrealname"]);
}
Sw. Close ();
Response. addheader ("content-disposition", "attachment; filename =" + server. urlencode (filepath ));
Response. contenttype = "application/MS-excel"; // specify that the returned stream cannot be read by the client and must be downloaded.
Response. writefile (filepath); // send the file stream to the client
Response. End ();
}
Method 2:
Void getdatatoexcel2 () // directly sent to the client
{
Sqlconnection conn = new sqlconnection ("Server =.; database = newlandcnbackupserver; uid = sa; Pwd = ");
Sqldataadapter da = new sqldataadapter ("select * From luser", Conn );
Dataset DS = new dataset ();
Da. Fill (DS, "luser ");
Datatable dt = Ds. Tables ["luser"];
Stringwriter Sw = new stringwriter ();
Sw. writeline ("userid \ tusername \ tuserrealname ");
Foreach (datarow DR in DT. Rows)
{
Sw. writeline (Dr ["userid"] + "\ t" + Dr ["username"] + "\ t" + Dr ["userrealname"]);
}
Sw. Close ();
Response. addheader ("content-disposition", "attachment; filename=userdata.xls ");
Response. contenttype = "application/MS-excel ";
Response. contentencoding = system. Text. encoding. getencoding ("gb2312 ");
Response. Write (SW );
Response. End ();
}