Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Code to export a datatable to a pdf file and a word file in c sharp using asp.net.
Posted
Comments
Sandeep Mewara 15-Oct-10 8:11am    
Any effort?
Smithers-Jones 15-Oct-10 12:18pm    
Too lazy to phrase a proper full sentence.

1 solution

<big>Export to PDF</big>

C#
//Get the data from database into datatable

string strQuery = "Select * from customers";

SqlCommand cmd = new SqlCommand(strQuery);

DataTable dt = GetData(cmd);

//Create a dummy GridView

GridView GridView1 = new GridView();

GridView1.AllowPaging = false;

GridView1.DataSource = dt;

GridView1.DataBind();

Response.ContentType ="application/pdf";

Response.AddHeader("content-disposition",

"attachment;filename=DataTable.pdf");

Response.Cache.SetCacheability(HttpCacheability.NoCache);

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

GridView1.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();

<big>Export to Word</big>

C#
//Get the data from database into datatable

string strQuery = "select * from customers";

SqlCommand cmd = new SqlCommand(strQuery);

DataTable dt = GetData(cmd);

//Create a dummy GridView

GridView GridView1 = new GridView();

GridView1.AllowPaging = false;

GridView1.DataSource = dt;

GridView1.DataBind();

Response.Clear();

Response.Buffer = true;

Response.AddHeader("content-disposition",

"attachment;filename=DataTable.doc");

Response.Charset = "";

Response.ContentType = "pplication/vnd.ms-word ";

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

GridView1.RenderControl(hw);

Response.Output.Write(sw.ToString());

Response.Flush();

Response.End();
 
Share this answer
 
v2
Comments
sweeneel 21-Oct-10 0:35am    
thanx for a good solution.....

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