using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
namespace GridViewSample
{
///
/// Converts ASP.Net 2.0 GridView to Excel files.
///
/// Written by Shay Friedman (http://www.IronShay.com).
/// You can use this freely without any worries.
///
public class GridViewToExcel
{
#region Grid to CSV
///
/// Converts a given GridView to a CSV file and sends it to the browser as the response stram
///
/// The filled GridView object to convert.
/// The filename that will appear to the user in the download dialog.
public static void ConvertGridToCSV(GridView grid, string fileName)
{
// Clear the response output stream before start
HttpContext.Current.Response.Clear();
// Set the response headers to fit our CSV file
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
using (StreamWriter writer = new StreamWriter(HttpContext.Current.Response.OutputStream))
{
// Add header row
writer.WriteLine(GetCSVLine(grid.HeaderRow.Cells));
// Add all the data rows
foreach (GridViewRow row in grid.Rows)
{
writer.WriteLine(GetCSVLine(row.Cells));
}
}
// End the current response. Otherwise, excel will open with the whole page inside.
HttpContext.Current.Response.End();
}
private static string GetCSVLine(TableCellCollection cellsToAdd)
{
string line = String.Empty;
bool isFirst = true;
foreach (TableCell cell in cellsToAdd)
{
if (!isFirst)
{
line += ",";
}
isFirst = false;
line += cell.Text;
}
return line;
}
#endregion
#region Grid to HTML
///
/// Converts the given grid to HTML and sends it back to the browser as an Excel file.
///
/// The grid to convert.
public static void ConvertGridToHTML(GridView grid)
{
string gridHTML = String.Empty;
using (StringWriter stringWriter = new StringWriter())
{
// Create a new page with a form element and the grid
Page page = new Page();
HtmlForm form = new HtmlForm();
form.Controls.Add(grid);
page.Controls.Add(form);
// Get the HTML of the page
HtmlTextWriter writer = new HtmlTextWriter(stringWriter);
page.RenderControl(writer);
writer.Flush();
// Get the html
gridHTML = stringWriter.ToString();
}
// Clear the response output stream before start
HttpContext.Current.Response.Clear();
// Set the response headers to fit our excel file
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Write(gridHTML);
// End the current response. Otherwise, excel will open with the whole page inside.
HttpContext.Current.Response.End();
}
#endregion
}
}