No more then a few paragraphs of things I want to archive (instead of try to remember)

Friday, June 22, 2007

Simple DataSet (DataGrid) to Excel

Below is a very simple DataSet (using a DataGrid) to Excel. The DataGrid, when rendered, is nothing more then an HTML Table. Microsoft Excel dose a great job of translating this to a worksheet.

TABLE == Excel Worksheet
TR == Excel Row
TD == Excel Cell


    private void DisplayPrimitiveExportReport(DataSet dsDataSet)
    {
        
// clear out and set the response stream
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Charset =
"";
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType =
"application/vnd.ms-excel";
        Response.AddHeader(
"Content-Disposition", "attachment; filename=ExcelReport.xls");

        
// set up the in mem datagrid
        DataGrid dg = new DataGrid();
        dg.DataSource = dsDataSet.Tables[0];

        dg.DataBind();

        
// render the datagrid to HTML
        StringWriter stringWrite = new StringWriter();
        
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        dg.RenderControl(htmlWrite);

        
// output the HTML (from datagrid)
        Response.Write(stringWrite.ToString());
        Response.End();
    }



This same method can be used with Word (using a content type of "application/word").

0 comments: