Export in Excel from datatable

// these namespaces need to be added to your code behind file
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace MySpot.UserPages
{
    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)
        {
            if (!IsPostBack)
            {
            }
        }

        // 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);
            sda.Fill(dt);
            ExportTableData(dt);
        }

        // this does all the work to export to excel
        public void ExportTableData(DataTable dtdata)
        {
            string attach = “attachment;filename=journal.xls”;
            Response.ClearContent();
            Response.AddHeader(“content-disposition”, attach);
            Response.ContentType = “application/ms-excel”;
            if (dtdata != null)
            {
                foreach (DataColumn dc in dtdata.Columns)
                {
                    Response.Write(dc.ColumnName + “\t”);
                    //sep = “;”;
                }
                Response.Write(System.Environment.NewLine);
                foreach (DataRow dr in dtdata.Rows)
                {
                    for (int i = 0; i < dtdata.Columns.Count; i++)
                    {
                        Response.Write(dr[i].ToString() + “\t”);
                    }
                    Response.Write(“\n”);
                }
                Response.End();
            }
        }
    }
}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s