Click here to Skip to main content
14,872,784 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Expert,

I am developing website in asp.net.with my sql as database.
I am exporting datatable results in excel sheet.

I am fetching results from 2 table - one in inquiry and other is inquiry_event_assigned

inquiry table contains details information regarding inquiry.
In inquiry form there is multiple event selection option.
These events are stored in inquiry_event_assigned table.
This table contains (inquiry_event_id,inquiry_id,event_id) .

I am using following method to generate excel

protected void ExportToExcel(DataTable dt)
    {
        try{
        if (dt.Rows.Count > 0)
        {

            string filename = "Inquiry Reports.xls";

            string excelHeader = "Inquiry Report";

            System.IO.StringWriter tw = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

            DataGrid dgGrid = new DataGrid();

            dgGrid.DataSource = dt;
            dgGrid.BorderStyle = BorderStyle.None;

            dgGrid.DataBind();

            // Report Header

            hw.WriteLine("<b><u><font size=’3′> " + excelHeader + " </font></u></b>");

            //Get the HTML for the control.

            dgGrid.RenderControl(hw);

            //Write the HTML back to the browser.

            //Response.ContentType = "application/vnd.ms-excel";

            Response.ContentType = "application/vnd.ms-excel";

            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");

            this.EnableViewState = false;

            Response.Write(tw.ToString());

            Response.End();
            }
           }
            catch(Exception ex1)
            {
            }
    

        }


It export all the results in excel sheet one by one,means if perticuler inquiry associated with multiple events exports one after another.

If there is more than one events associted with perticuler inquiry they must be in single cell with comma separated.

like.

Build Expo Kenya,Auto Afrika	Telemarketing	afsr@gest.com	Automotive	India	12/25/2011 0:00	In-Progress


Thanks in advance
Posted

Try this
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900