I have a piece of code that generates an Excel file from a dataset. I
want to be able to write it to a file, then email it as an attachment.
Is there any way I can direct the output of response.write to a file?
Here is my code:

public static void ExportDataSetToExcel(DataSet ds, string filename)
    {
        HttpResponse response = HttpContext.Current.Response;
        response.ContentEncoding =
Encoding.GetEncoding("windows-1252");


        // first let's clean up the response.object
        response.Clear();
        response.Buffer = true;
        response.Charset = "UTF-8";

        // set the response mime type for excel
        response.ContentType = "application/vnd.ms-excel";
        response.AddHeader("content-disposition",
string.Format("attachment;filename={0}.xls", filename));

        // create a string writer
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                const string style = @"<style> .text { mso-number-
format:\#\; } </style> ";

                // instantiate a datagrid
                DataGrid dg = new DataGrid();
                dg.DataSource = ds.Tables[0];
                // to prevent xl mutilating part numbers etc
                for (int i = 0; i < dg.Items.Count; i++)
                {
                    DataGridItem item = dg.Items[i];
                    for (int j = 0; j < item.Cells.Count; j++)
                    {
                        item.Cells[j].Attributes.Add("class", "text");

                    }
                }
                //
                dg.DataBind();
                dg.RenderControl(htw);
                response.Write(style);


                response.Write(sw.ToString());
                response.End();
            }
        }



    }

-- 
You received this message because you are subscribed to the Google
Groups "DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML
Web Services,.NET Remoting" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/dotnetdevelopment?hl=en?hl=en
or visit the group website at http://megasolutions.net

Reply via email to