//You use these variables throughout the application.
string fileExcel, filePath, fileName, strLine, sql;
FileStream objFileStream;
StreamWriter objStreamWriter;
Random nRandom = new Random(DateTime.Now.Millisecond);
SqlConnection cnn = new SqlConnection("server=(local);database=pubs;Integrated Security=SSPI");
//Create a random file name.
fileExcel = "t" + nRandom.Next().ToString() + ".xls";
//Set a virtual folder to save the file.
//Make sure to change the application name to match your folder.
filePath = Server.MapPath("\\ExcelCSTest");
fileName = filePath + "\\" + fileExcel;
//Use FileSystem objects to create the .xls file.
objFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream);
//Use a DataReader object to connect to the Pubs database.
cnn.Open();
sql = "select au_id,au_lName,au_fname,phone,address,city,state,zip,contract from authors";
SqlCommand cmd = new SqlCommand(sql, cnn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
//Initialize the string that is used to build the file.
strLine = "";
//Enumerate the field names and the records that are used to build
//the file.
for (int i = 0; i <= dr.FieldCount-1; i++)
{
strLine = strLine + dr.GetName(i).ToString() + Convert.ToChar(9);
}
//Write the field name information to the file.
objStreamWriter.WriteLine(strLine);
//Reinitialize the string for data.
strLine = "";
//Enumerate the database that is used to populate the file.
while (dr.Read())
{
for (int i = 0; i <= dr.FieldCount-1; i++)
{
strLine = strLine + dr.GetValue(i).ToString() + Convert.ToChar(9);
}
objStreamWriter.WriteLine(strLine);
strLine="";
}
//Clean up.
dr.Close();
cnn.Close();
objStreamWriter.Close();
objFileStream.Close();
//Include a link to the Excel file.
HyperLink1.Text="Open Excel";
HyperLink1.NavigateUrl=fileExcel;