Prevent download when exporting Gridview to Excel - asp.net

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();

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";

Cannot export to Excel in IE 11

I have a web application that exports data from a gridview to Excel. It works fine in Chrome but doesn't work in IE 11 and Firefox. I see a lot of issues with this when I google it but this error seems to be unique.
protected void ExportToExcel(List<MapAmericas.Model.Project> Projects)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.AddHeader("content-disposition", "attachment;filename=MyFile" + DateTime.Now.ToString() + ".xls");
Response.Charset = "";
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.RowDataBound += new GridViewRowEventHandler(dataExportExcel_ItemDataBound);
gv.DataSource = Projects;
gv.DataBind();
gv.RenderControl(htw);
Response.Write(AddExcelStyling()); //this contains the opening html elements
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append(sw + "</body></html>");
Response.Write(sbResponseString.ToString());
Response.Flush();
Response.Close();
Response.End();
}
...and the issue I'm getting has to do with not being able to access Temporary Internet Files. I get a popup "Problems during Load" and about a dozen entries: "Missing File...Temporary Internet Files\Content\" and then I get a message reading "Unable to read file".
I had an image to represent the error but I'm not able to upload images.
When I click on one of the links, it loads up my webpage without any styles and I don't get an excel file.
Does anyone know what the issue would be?
I got it! I added 2 lines of code to my existing code and it works. See lines marked with **:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Panorama_Project-" + DateTime.Now.ToString() + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.RowDataBound += new GridViewRowEventHandler(dataExportExcel_ItemDataBound);
gv.DataSource = Projects;
gv.DataBind();
gv.RenderControl(htw);
HttpContext.Current.Response.Write(AddExcelStyling());
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append(sw + "</body></html>");
**HttpContext.Current.Response.AddHeader("Content-Length", sbResponseString.Length.ToString());**
HttpContext.Current.Response.Write(sbResponseString.ToString());
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.Close();
//HttpContext.Current.Response.End();
**System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();**
It seems as though it was trying to display the entire Response object which included my page and all linked resources. The Content-Length and replacing Reponse.End and Response.Flush with System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest() seems to do the trick.
This is the simplified version of an Export To Excel function (for a datatable) that I use and one that works for all the browsers. See if this helps. The code is quite similar to yours though:
public void ExportDataToExcel(String FileName, DataTable dtData)
{
// get gridview out of datatable
GridView gv = new GridView();
gv.AllowPaging = false;
gv.DataSource = dtData;
gv.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition",
"attachment;filename=" + FileName + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < gv.Rows.Count; i++)
{
// Apply text style to each Row
gv.Rows[i].Attributes.Add("class", "textmode");
}
gv.RenderControl(hw);
HttpContext.Current.Response.Output.Write(sw.ToString());
// commenting this out to resolve this error
// System.Web.HttpException: The remote host closed the connection.
// The error code is 0x800703E3.
// HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}

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/

Remove Image in excel header after exporting the gidview

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;
}

gridview to excel

work on asp.net vs05.when i export gridview to excel than i get the below error
RegisterForEventValidation can only be called during Render();
why i get this error .How to solve it?
public void ToExcel()
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
gvSearch.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
//-- added to handle special characters in excel
Response.ContentEncoding = Encoding.Unicode;
Response.BinaryWrite(Encoding.Unicode.GetPreamble());
gvSearch.EnableViewState = false;
//-- added to handle special characters in excel
Add these lines and see if it helps.
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
gvSearch.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();
}
It's a shot in the dark.
in aspx page, Change the following to false : AllowPaging="False" AllowSorting="False" and remove Pagesize="10".
This Code Help to solve export Gridview to excel related problem
Microsoft.Office.Interop.Excel._Application app = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook =
app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Excel Sheet Name"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for (int i = 1; i < Gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = Gridview.Columns[i - 1].HeaderText;
}
for (int i = 0; i < Gridview.Rows.Count; i++)
{
for (int j = 0; j < Gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] =
Gridview.Rows[i].Cells[j].Value.ToString();
}
}

Resources