.

Monday, January 5, 2009

Export GridView and Save into web Server

public void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();

// add the header row to the table
if (gv.HeaderRow != null)
{
this.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
//gv.DataBind();
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{

this.PrepareControlForExport(row);
table.Rows.Add(row);
}

// add the footer row to the table
if (gv.FooterRow != null)
{
this.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}

// render the table into the htmlwriter
table.RenderControl(htw);


Stream fsExportFile = new FileStream(Server.MapPath("~/Upload/EdvImage/") + _exlFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
System.IO.MemoryStream memStr;
System.Text.ASCIIEncoding myEncoder = new System.Text.ASCIIEncoding();
byte[] bytes = myEncoder.GetBytes(htw.InnerWriter.ToString());
memStr = new MemoryStream(bytes);
memStr.WriteTo(fsExportFile);
fsExportFile.Close();
}
}


}

No comments:

.