using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Whatever {
///
/// This class provides a method to write a dataset to the HttpResponse as
/// an excel file.
///
public class ExcelExport {
public static void ExportDataSetToExcel(DataSet ds, string filename) {
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter()) {
using (HtmlTextWriter htw = new HtmlTextWriter(sw)) {
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
}
}
You could of cource use a DataTable instead of the DataSet.
Tim's post is availible here

3 comments:
hi
i would like to export a datagrid from asp to excel.
the code givven is great but i need to save the excel file in the backgroud of the application
without opening the page or showing the "save as" pop up.
do have any idea how to do it?
i used file.creat with a filestream but it does not save as mime type of excel which makes problems after.
thank you
I have never done this in a web page, but I have done something similar in a forms application. The approach I used was to create a template in Excel and save it as XML. You can then, from your code in the webpage, generate the same type of XML and save it to disk. You have to save the file with the xml-extension. The content in the file will tell Windows that is is a file that should be opened in Excel.
There is good tool which works with excel files and possible more than-fix Excel tools,it has free status as far as I can see,also software works on a very important report, with statistical data, graphics, tables and a lot of critical information and it is lost at once,will analyze your damaged document and show you its content in a preview window,allow you to fix files Excel and see, which elements will be recovered and which are damaged too badly,can choose, whether you'd like to recover all of your damaged documents manually and spend many days for this purpose.
Post a Comment