Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Feb 11, 2012 04:40 PM|LINK
Moderators, if this should go into another forum that is more appropriate, please feel free to place it there.
I've seen a lot of examples of how to export data into an Excel spreadsheet using ASP.NET and most have been wrong.
This code works and is very simple to follow.
This is my first contribution to the forums, enjoy...Paul
// these namespaces need to be added to your code behind file
public partial class Journal : System.Web.UI.Page
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySpotDBConnStr"].ConnectionString);
DataTable dt = new DataTable();
// regular page_load from .aspx file
protected void Page_Load(object sender, EventArgs e)
// added a button with ID=btnDownload and double clicked it's onclick event to auto create method
protected void btnDownload_Click(object sender, EventArgs e)
string queryStr = "SELECT * from table";
SqlDataAdapter sda = new SqlDataAdapter(queryStr, conn);
// this does all the work to export to excel
public void ExportTableData(DataTable dtdata)
string attach = "attachment;filename=journal.xls";
Response.ContentType = "application/ms-excel";
if (dtdata != null)
foreach (DataColumn dc in dtdata.Columns)
Response.Write(dc.ColumnName + "\t");
//sep = ";";
foreach (DataRow dr in dtdata.Rows)
for (int i = 0; i < dtdata.Columns.Count; i++)
Response.Write(dr[i].ToString() + "\t");
In IE9 the regular bar comes on down at the bottom asking to save or open, just click open and there it is
In FireFox that pesky download box comes on, then pops up a dialog, click open and there it is
in Opera it asks to save or open, click open and there it is.