badzster
asked on
Simple Code to export plain text only from Gridview to CSV (no formatting)
I have the following code in Test.vb:
This code accesses GridViewExportUtil.cs which has the following code:
I need help with the following:
(1) The export works great except the output still includes the background color of the last column - I can't remove it for some reason.
(2) Since the GridViewExportUtil.cs removes the images from the first column and replaces it with the Alt text, the first column is blank. Is there a way to remove this column?
I just want a plain csv file which opens in excel...
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
This code accesses GridViewExportUtil.cs which has the following code:
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);
}
}
}
}
I need help with the following:
(1) The export works great except the output still includes the background color of the last column - I can't remove it for some reason.
(2) Since the GridViewExportUtil.cs removes the images from the first column and replaces it with the Alt text, the first column is blank. Is there a way to remove this column?
I just want a plain csv file which opens in excel...
Why did not work with underlying data source of the grid view?
ASKER
Would you have a sample? I presume you mean why didn't I export directly from the datasource rather than the gridview??
If you just need plain text you need to remove the style code below used in the header in Export method:
Regarding second issue: Remove the first column of the datatable using
RemoveAt method
for (int j = 0; j < gv.Columns.Count; j++)
{
gv.HeaderRow.Cells[j].Style.Add("background-color", "cornflowerblue");
}
Regarding second issue: Remove the first column of the datatable using
RemoveAt method
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.
Here is an example of exporting to CSV format from a SqlDataReader:
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();
}
Hi,
Check this article - http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
Well explained all the possible formats in which you can export the data!
Hope it helps u...
Check this article - http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
Well explained all the possible formats in which you can export the data!
Hope it helps u...
ASKER
Tried the following code from the suggested link (http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx) but only the headers appear - no rows...definitely rows in gridview though??
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();
}
Hi,
I created a sample code for you -
The above is a sample code, which it shows how to export the data as CSV format!
Moreover, you would have been using Templates instead of Auto Generated columns and hence it is not exporting the data!
http://forums.asp.net/t/1736121.aspx/1
Hope it helps u...
I created a sample code for you -
<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();
}
The above is a sample code, which it shows how to export the data as CSV format!
Moreover, you would have been using Templates instead of Auto Generated columns and hence it is not exporting the data!
http://forums.asp.net/t/1736121.aspx/1
Hope it helps u...
ASKER
Thanks for the effort - I've tried the code below (converted to vb) but keep getting the error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceExcept ion: Object reference not set to an instance of an object.
Source Error:
Line 293: Dim lt As Literal = TryCast(gvCA.Rows(i).FindC ontrol("La bel1"), Literal)
Line 294: 'add separator
Line 295: sb.Append(lt.Text + ","c)
Any reason you can think of?
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceExcept
Source Error:
Line 293: Dim lt As Literal = TryCast(gvCA.Rows(i).FindC
Line 294: 'add separator
Line 295: sb.Append(lt.Text + ","c)
Any reason you can think of?
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]()
ASKER
Already tried that as per my post on 2013-01-06 at 09:19:14 ID: 38748197
I just wish there was a way to export directly from the SQLDataSource - however the sample given by: P1ST0LPETEPosted on 2013-01-06 at 01:30:03ID: 38747792 doesn't seem to specify/allow you to input the specific SQLDataSource...maybe I'm missing something.
I just wish there was a way to export directly from the SQLDataSource - however the sample given by: P1ST0LPETEPosted on 2013-01-06 at 01:30:03ID: 38747792 doesn't seem to specify/allow you to input the specific SQLDataSource...maybe I'm missing something.
Hi,
Yeah! It's because you have used asp:Label control and while casting you have used asp:Literal control, which leads to the NullReference Exception!
Consider the following statement in your code -
You have asp:Label in the GridView, but you are casting it to asp:Literal which is not correct.
In my example, i have used Literals, so i have used same in the code behind as well -
So, you have to use the same control which you have used in the asp:GridView and cast it accordingly!
If you still has issues, do show us the asp:GridView code, so that we will give the equivalent code!
Hope it helps u...
Yeah! It's because you have used asp:Label control and while casting you have used asp:Literal control, which leads to the NullReference Exception!
Consider the following statement in your code -
Dim lt As Literal = TryCast(gvCA.Rows(i).FindControl("Label1"), Literal)
You have asp:Label in the GridView, but you are casting it to asp:Literal which is not correct.
In my example, i have used Literals, so i have used same in the code behind as well -
<asp:Literal Text='<%#Eval("Name")%>' ID="txt1" runat="server" />
So, you have to use the same control which you have used in the asp:GridView and cast it accordingly!
If you still has issues, do show us the asp:GridView code, so that we will give the equivalent code!
Hope it helps u...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Open in new window