Export to Excel sheet from Datagrid
-
Need help on exporting to excel from datagrid. (I dont want third party tool). I tried to render the data to HTML as given below:
//first let's clean up the response.object
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = false;//set the response mime type for excel
response.ContentType = "application/ms-excel";response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", StrFileName));
//create a string writer
StringWriter stringWrite = new StringWriter();//create an htmltextwriter which uses the stringwriter
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);//instantiate a datagrid
DataGrid dg = new DataGrid();//set the datagrid datasource to the dataset passed in
dg.DataSource = dr;//bind the datagrid
dg.DataBind();//tell the datagrid to render itself to our htmltextwriter
dg.RenderControl(htmlWrite);//all that's left is to output the html
response.Write(stringWrite.ToString());
response.End();It works fine if i edit the file and save. I tried to create new worksheet in the same excel file and saved this changes, new temp folder has been created. (filename_files as like HTML files if you save any web page) Please let me know how to avoid this?
Harini