Remove Image in excel header after exporting the gidview - asp.net

Kindly help me on how to remove image in my excel header. I generate the excel using export command using gridview as source data
here is my code
Response.AddHeader("content-disposition", "attachment;filename=" & strFilename & ".xls")
Response.Clear()
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
Dim htw As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(sw)
grvData.AllowPaging = False
grvData.AllowSorting = False
PopulateGrid()
grvData.RenderControl(htw)
Response.Write(sw.ToString)
Response.End()
Everything was set -except that one my header had a blank header name because of the image that was now shown - the image is came from gridview (I'm using arrow for asc and desc) - sorry i cant post any image here now

Give this ClearControls method a shot. It should remove any controls from the Grid before exporting:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(DataGrid1);
DataGrid1.RenderControl(oHtmlTextWriter);
DataGrid1.GridLines = GridLines.Both;
DataGrid1.Style.Clear();
Response.Write(oStringWriter.ToString());
Response.End();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
}
catch
{
//do nothing
}
finally
{
control.Parent.Controls.Remove(control);
}
}
else
{
if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
}
return;
}

Related

Export to CSV Website asp

I have a GridView and when I click Export Button to export my data into CSV. I click the button and it takes all the data correctly but it doesn't show anything, no popup to ask me to open or to save .
Here is my code
protected void btnExport_Click(object sender, EventArgs e)
{
ExportCSV();
}
protected void ExportCSV()
{
GridViewSW.DataSource = ViewState["source"];
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Orders.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridViewSW.AllowPaging = false;
GridViewSW.DataBind();
StringBuilder columnbind = new StringBuilder();
for (int k = 0; k < GridViewSW.Columns.Count; k++)
{
columnbind.Append(GridViewSW.Columns[k].HeaderText + ",");
}
columnbind.Append("\r\n");
for (int i = 0; i < GridViewSW.Rows.Count; i++)
{
for (int j = 0; j < GridViewSW.Columns.Count; j++)
{
columnbind.Append(GridViewSW.Rows[i].Cells[j].Text + ",");
}
columnbind.Append("\r\n");
}
Response.Output.Write(columnbind.ToString());
Response.Flush();
Response.End();
}
NEW EDIT
I changed the code a little bit. Now i have the csv file and he has all the data in, but when I click the button it doesn't show any dialog box with open or save.
string fullSavePath = HttpContext.Current.Server.MapPath(string.Format("~/csv/Orders.csv"));
StreamWriter sr = new StreamWriter(fullSavePath);
DataSet ds = (DataSet)ViewState["source"];
MyDateTime date = new MyDateTime();
DataTableReader dr = ds.Tables[0].CreateDataReader();
while (dr.Read())
{
sr.Write(dr.GetValue(0) + "," + date.ConvertToDate(Convert.ToInt64(dr.GetValue(2))) + "," + date.ConvertToDate(Convert.ToInt64(dr.GetValue(3))) + "," + dr.GetValue(4) + "\r\n");
}
sr.Flush();
sr.Close();
sr.Dispose();
System.IO.FileInfo file = new System.IO.FileInfo(fullSavePath);
System.Web.HttpContext context = System.Web.HttpContext.Current;
System.Web.HttpResponse response = context.Response;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename =" + "Orders.csv"));
// Response.TransmitFile(fullSavePath);
Response.WriteFile(file.FullName);
// Response.Flush();
context.ApplicationInstance.CompleteRequest();
// Response.End();
// Response.Close();
I believe you need to change your content type to "text/csv"
Response.ContentType = "text/csv";

Prevent download when exporting Gridview to Excel

I am trying to export data in a Gridview to Excel and store that file in a folder on server.
I have done this part. The only thing I want to do is,
I want to prevent downloading the Excel file.
Please find my code below.
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "order.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridX.AllowPaging = false;
bindX();
gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
{
gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gridX.RenderControl(htw);
//Response.Write(sw.ToString());
string renderedGridView = sw.ToString();
string path = Server.MapPath("~/Order/od/x");
System.IO.File.WriteAllText(path + "/order" + lblF.Text + ".xls", renderedGridView);
sw.Close();
htw.Close();
Thanks in advance.
Use this code by editing as per your need :
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
e.Cancel = true;
WebClient client = new WebClient();
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(e.Url);
}
void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
string filepath = textBox1.Text;
File.WriteAllBytes(filepath, e.Result);
MessageBox.Show("File downloaded");
}
Hope this will help you.
I got the answer.
Code
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridX.AllowPaging = false;
bindX();
gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
{
gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gridX.RenderControl(htw);
//Response.Write(sw.ToString());
string renderedGridView = sw.ToString();
string path = Server.MapPath("~/Order/od/x");
System.IO.File.WriteAllText(path + "/order" + lblF.Text + ".xls", renderedGridView);
sw.Close();
htw.Close();

wrong output when transfering datagrid to word/excel/pdf

hye, i have made this code which i have tried separately from my current web and it work perfectly but when i combine it with my web, i didn't get the output that was generated in the gridview. here is the code that i had used.
protected void Wordbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
wordmax();
}
if (curdata.Checked == true)
{
wordcur();
}
}
protected void excelbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
excelmax();
}
if (curdata.Checked == true)
{
excelcur();
}
}
protected void pdfbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
pdfmax();
}
if (curdata.Checked == true)
{
pdfcur();
}
}
public void wordmax()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=MaxdataExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
gridmaxdata.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void wordcur()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=CurrentDataExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
gridcurdata.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void excelmax()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=MaxDataExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
//Change the Header Row back to white color
gridmaxdata.HeaderRow.Style.Add("background-color", "#FFFFFF");
gridmaxdata.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void excelcur()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=CurrentdataExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
//Change the Header Row back to white color
gridcurdata.HeaderRow.Style.Add("background-color", "#FFFFFF");
gridcurdata.RenderControl(hw);
//---------------------------------------------------------------------------------
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void pdfmax()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=MaxDataExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
gridmaxdata.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
public void pdfcur()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=CurrentdataExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
gridcurdata.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
this is the code that i used to create the datagridview
public void maxdatatable()
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\webradiation\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True";
//Bind SQLDataSource to GridView for max data
// Create SQLDataSource.
SqlDataSource sqlDataSource1 = new SqlDataSource();
sqlDataSource1.ID = "SqlDataSource123";
this.Page.Controls.Add(sqlDataSource1);
// Bind ConnectionString to SQLDataSource.
sqlDataSource1.ConnectionString = connectionString;
// Retrieve records
sqlDataSource1.SelectCommand = "SELECT top 30 [date], [data] FROM [loc1] WHERE (([data] >= '2') AND (([date] >= '" + combdatetime11.ToString() + "') AND ([date] <= '" + combdatetime21.ToString() + "'))) ORDER BY [data] DESC, [date] DESC";
gridmaxdata.DataSource = sqlDataSource1;
gridmaxdata.DataBind();
}
public void currdata()
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\webradiation\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True";
// Create SQLDataSource.
SqlDataSource sqlDataSource2 = new SqlDataSource();
sqlDataSource2.ID = "SqlDataSource12";
this.Page.Controls.Add(sqlDataSource2);
// Bind ConnectionString to SQLDataSource.
sqlDataSource2.ConnectionString = connectionString;
// Retrieve records
sqlDataSource2.SelectCommand = "SELECT [date], [data] FROM [loc1] WHERE (([date] >= '" + combdatetime11.ToString() + "') AND ([date] < '" + combdatetime21.ToString() + "'))";
gridcurdata.DataSource = sqlDataSource2;
gridcurdata.DataBind();
}
for the word document, the output that i got is
(div) (/div)
*i have to used "(" and ")" to replace "<" and ">" because this pageweb make it disappear
the excel is like this
(style) .textmode { mso-number-format:\#; } (/style)(div)(div)
the pdf file i got an error saying that the document does not have pages.
do you not where did i do wrong?
you can create a extension function to convert the datasource datatable to excel and then send it to client using Response.WriteFile method
using OfficeOpenXml;
public static class Extensions
{
public static void ToExcel(this DataTable source, string destinationXlsxPath)
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Data");
ws.Cells["A1"].LoadFromDataTable(source, true);
FileInfo file = new FileInfo(destinationXlsxPath);
pck.SaveAs(file);
}
}
}
EPPlus: http://epplus.codeplex.com/

Export from GridView to Excel save popup not working

I want to export data from GridView into an excel file on ASP.NET website. I added a GridView only for this purpose
<body>
<form id="mainForm" runat="server">
<asp:GridView ID="exportGrid" runat="server">
</asp:GridView>
</form>
....
</body>
In codebehind I have this:
public override void VerifyRenderingInServerForm(Control control) { }
var result = GetDataIQueryable(); //A method that returns an IQueryable
exportGrid.DataSource = result;
exportGrid.DataBind();
Response.Clear();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + "ExcelFile.xls");
Response.ContentType = "application/excel";
var sw = new System.IO.StringWriter();
var htw = new HtmlTextWriter(sw);
exportGrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
The problem is that the popup that allows me to save the excel file on my computer is not appearing. What should I change in my code ?
Use this code on your button click event
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FormReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
BindGridView();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
GridView1.Dispose();
}
}
#endregion
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
and on .aspx page use
<%# Page Title="" Language="C#" EnableEventValidation="false"%>
I know this is a bit too late, but i am posting this just for information. I found the answer in the comments but i would still like to submit a answer with code , because i myself found it difficult to find the code so the answer is for if your grid is inside update panel. You need to add a post back trigger to the button.
private void RegisterPostBackControl()
{
ScriptManager.GetCurrent(this).RegisterPostBackControl(yourButton);
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
Your Buttons Click Event :
protected void yourButton_Click(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "full", true);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FormReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
yourGrid.AllowPaging = false;
var emps = FunctionThatGetsGridValues();
yourGrid.DataSource = emps;
yourGrid.DataBind();
yourGrid.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in yourGrid.HeaderRow.Cells)
{
cell.BackColor = yourGrid.HeaderStyle.BackColor;
}
foreach (GridViewRow row in yourGrid.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = yourGrid.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = yourGrid.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
yourGrid.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
yourGrid.Dispose();
}
}
And On Page Load Dont forget to add :
protected void Page_Load(object sender, EventArgs e)
{
this.RegisterPostBackControl();
}

How to remove paging text in excel sheet while exporting data from GridView to Excelsheet?

I implemented export to excel functionality in asp.net application.Here i export data from Grid-view to excel-sheet.I also applied Paging in Grid-view.
So when i export data from Grid-view to excel sheet,paging text also display in excel sheet as shown in the given image.
How can we remove it
i follow the below approach for exporting data
Code-Behind:
Response.Clear()
Response.ClearHeaders()
Response.AddHeader("content-disposition", "attachment;filename=sample.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Dim sb As StringBuilder = New StringBuilder()
Dim objStringWriter As StringWriter = New StringWriter(sb)
Dim objHtmlTextWriter As HtmlTextWriter = New HtmlTextWriter(objStringWriter)
//gvSample is Gridview server control
gvSample.RenderControl(objHtmlTextWriter)
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble())
Response.Write(objStringWriter)
Response.End()
Thanks
Before rendering - disable the paging, bind the data and then render:
gvSample.AllowPaging = false;
gvSample.DataSource = ds; //Data Source
gvSample.DataBind();
gvSample.RenderControl(objHtmlTextWriter)
when ever to get the data from database for show the gridview,before that but the result content in viewstate[""] after the reuse it. when search the data for filter the main content the updated data will present in the viewstate, so you will get correct data to export
gvSample.AllowPaging = false;
gvSample.DataSource = ViewState["vsData"]; //Data Source
gvSample.DataBind();
gvSample.RenderControl(objHtmlTextWriter);
It works using SQL DataSourceID
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
other attached asp coding file
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["ondblclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Edit$" + e.Row.RowIndex);
e.Row.Attributes["style"] = "cursor:pointer";
}
}

Resources