error showing while data export gridview to excel,word,pdf

Posted by Vibheesh under C# on 3/26/2012 | Points: 10 | Views : 4572 | Status : [Member] | Replies : 1
// when export to excel , button click the data showing in excel sheet and while i am trying to save after opened it is saved in .htm format
the code given below please help me ,if i give yes it will save in .htm format, i want to save in .Xls format
// excel code
string attachment = "attachment; filename=Export.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(htw);
// .word code

Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(htmlWrite);
//GridView1.RenderControl(htw);
Response.Write(stringWrite.ToString());
Response.End();
//.pdf code

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();


//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
//the same problem coming while try to save in word and pdf




Responses

Posted by: Sksamantaray on: 3/26/2012 [Member] Silver | Points: 25

Up
0
Down
Whats the exact error you get?

Thanks,
Sanjay

Vibheesh, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response