Protected Sub ibExportPlain_Click(ByVal sender As Object, ByVal args As EventArgs) Handles ibExportPlain.Click, lbExportPlain.Click
GridViewExportUtil.Export("Export.csv", Me.gvCA)
End Sub
using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
///
/// </summary>
public class GridViewExportUtil
{
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <param name="gv"></param>
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "text/plain";
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)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
for (int j = 0; j < gv.Columns.Count; j++)
{
gv.HeaderRow.Cells[j].Style.Add("background-color", "cornflowerblue");
}
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is Image)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as Image).AlternateText));
}
else if (current is Label)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as Label).Text));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
GridViewExportUtil.PrepareControlForExport(current);
}
}
}
}
for (int j = 0; j < gv.Columns.Count; j++)
{
gv.HeaderRow.Cells[j].Style.Add("background-color", "cornflowerblue");
}
table.Columns.RemoveAt(0);
before render the table into the htmlwriter.
Would you have a sample? I presume you mean why didn't I export directly from the datasource rather than the gridview??I agree that you should do the export from the underlying data source. Attempting to export from the GridView itself just seems dirty.
public String ExportToCsv(SqlDataReader reader)
{
var csv = new StringBuilder();
if (reader != null && reader.HasRows)
{
var count = reader.FieldCount;
for (int i = 0; i < count; i++)
{
csv.AppendFormat("{0}{1}", reader.GetName(i), i < count - 1 ? "," : "\r\n");
}
while (reader.Read())
{
for (int i = 0; i < count; i++)
{
csv.AppendFormat("{0}{1}", Convert.ToString(reader[i]), i < count - 1 ? "," : "\r\n");
}
}
}
return csv.ToString();
}
protected void btnExportCSV_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
<asp:GridView runat="server" ID="gridView" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="A" ShowHeader="true" >
<ItemTemplate>
<asp:Literal Text='<%#Eval("Name")%>' ID="txt1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="B">
<ItemTemplate>
<asp:Literal runat="server" ID="txt2" Text='<%#Eval("Company")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C">
<ItemTemplate>
<asp:Literal runat="server" ID="txt3" Text='<%#Eval("Category")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
var rows = new []
{
new
{
Name="Bill Gates", Company="Microsoft",Category = "Software"
},
new
{
Name="Steve Jobs",Company="Apple",Category = "Software"
},
new
{
Name="Larry Page",Company="Google",Category = "Software"
}
};
gridView.DataSource = rows;
gridView.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
StringBuilder sb = new StringBuilder();
for (int k = 0; k < gridView.Columns.Count; k++)
{
//add separator
sb.Append(gridView.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < gridView.Rows.Count; i++)
{
Literal lt = gridView.Rows[i].FindControl("txt1") as Literal;
//add separator
sb.Append(lt.Text + ',');
lt = gridView.Rows[i].FindControl("txt2") as Literal;
//add separator
sb.Append(lt.Text + ',');
lt = gridView.Rows[i].FindControl("txt3") as Literal;
//add separator
sb.Append(lt.Text + ',');
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
gvCA.DataBind()
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv")
Response.Charset = ""
Response.ContentType = "application/text"
Dim sb As New StringBuilder()
For k As Integer = 0 To gvCA.Columns.Count - 1
'add separator
sb.Append(gvCA.Columns(k).HeaderText + ","c)
Next
'append new line
sb.Append(vbCr & vbLf)
For i As Integer = 0 To gvCA.Rows.Count - 1
Dim lt As Literal = TryCast(gvCA.Rows(i).FindControl("Label1"), Literal)
'add separator
sb.Append(lt.Text + ","c)
lt = TryCast(gvCA.Rows(i).FindControl("LinkButton2"), Literal)
'add separator
sb.Append(lt.Text + ","c)
lt = TryCast(gvCA.Rows(i).FindControl("Label2"), Literal)
'add separator
sb.Append(lt.Text + ","c)
lt = TryCast(gvCA.Rows(i).FindControl("Label3"), Literal)
'add separator
sb.Append(lt.Text + ","c)
lt = TryCast(gvCA.Rows(i).FindControl("lblDueDate"), Literal)
'add separator
sb.Append(lt.Text + ","c)
lt = TryCast(gvCA.Rows(i).FindControl("Label5"), Literal)
'add separator
sb.Append(lt.Text + ","c)
lt = TryCast(gvCA.Rows(i).FindControl("Label6"), Literal)
'add separator
sb.Append(lt.Text + ","c)
'append new line
sb.Append(vbCr & vbLf)
Next
Response.Output.Write(sb.ToString())
Response.Flush()
Response.[End]()
Dim lt As Literal = TryCast(gvCA.Rows(i).FindControl("Label1"), Literal)
<asp:Literal Text='<%#Eval("Name")%>' ID="txt1" runat="server" />
Open in new window