DataExport to Excel Error - asp.net

Hi I am trying Export data to excel sheet from GridView but having this error.
RegisterForEventValidation can only be called during Render();
Here is my code
Dim attachment As String
attachment = "attachment; filename=Contacts.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/ms-excel"
Dim myStringWriter As New IO.StringWriter
Dim myhtmlStringWriter As New HtmlTextWriter(myStringWriter)
GridView1.RenderControl(myhtmlStringWriter)
Response.Write(myStringWriter.ToString)
Response.End()
Thanks

You can do this in the web.config file but in this case the eventValidation will be turned off for all the pages.
or you can do this in the Page directive which will turn off the validation for a single page.

Related

Why the TransmitFile is not downlaoding the file?

I am downloading a file from folder but this code of me doesn't download. It doesn't throw any error but doesn't download either.
Dim req As WebClient = New WebClient()
Dim response As HttpResponse = HttpContext.Current.Response
Dim filePath As String = "~/Downloads/MyExcelFile.xls"
response.Clear()
response.ClearContent()
response.ClearHeaders()
response.Buffer = True
response.AddHeader("Content-Disposition", "attachment;filename=Filename.extension")
'Dim data As Byte() = req.DownloadData(Server.MapPath(filePath))
'response.BinaryWrite(data)
response.TransmitFile(Server.MapPath(filePath))
'response.End()
try
response.WriteFile("some file");
response.Flush();
response.Close();
also consider Andrew's response on handler type - ashx is usually cleaner, with webform you might have other things that happen during page life cycle.

Convert excel file to byte array

I'm using ASP.net with VB codebehind.
I need to be able to convert an excel file created in code into a byte array in order to send it to the client. Without saving the file to the server.
this is how i created the excel document
Dim APP As Excel.Application = New Excel.Application
Dim missing As Object = System.Reflection.Missing.Value
Dim Workbook As Excel.Workbook = (APP.Workbooks.Add(missing))
Dim worksheet As Excel.Worksheet = Workbook.ActiveSheet
'..Fill cells in worksheet..
This is how i transmit it:
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.Cookies.Clear()
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.CacheControl = "private"
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8
Response.AppendHeader("Content-Length", filebytes.Length.ToString())
Response.AppendHeader("Pragma", "cache")
Response.AppendHeader("Expires", 60)
Response.AppendHeader("Conetnt-Disposition", "attachement; filename='MostIssuesByModelReport.xlsx'; size=" & filebytes.Length.ToString() & "; creation-date=" & Date.Now.ToString("R") & "; modification-date=" & Date.Now.ToString("R") & "; read-date=" & Date.Now.ToString("R"))
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'write to client
Response.BinaryWrite(filebytes)
Response.End()
I just need to get the content of Workbook into filebytes
EDIT:
After looking around a bit more I can now make it download a file, however this file does not use the filename specified in the above code, it uses the name of the asp server page that the user is on, it also has a .aspx extension..however if I force it to open in excel it is correct. Besides popping up saying the source may be corrupted. Why is this happening and how can I fix it?

Clearing a Response in Postback to download text file from Button Click

Now... I could do this is a separate page, but i don't want to!
I am trying to create a service which fetches a load of JS files required for a project, compresses them and downloads a single file, but what it does isn't really the issue, the downloading bit is not behaving as expected.
From many examples on here, including:
In ASP.NET, how to get the browser to download string content into a file? (C#)
I have the (simplified) code:
Sub Download() Handles button.click
var AllTheScript as string ="blah blah blah"
Response.Buffer = True
Response.Clear()
Response.ClearContent()
Response.Write(AllTheScript)
Response.ContentType = "application/text"
Response.AddHeader("content-disposition", "attachment; filename=myJavascript.js")
Response.Flush()
End Sub
Obviously, I also have an <asp:button id="button" runat="server"/> element in my page.
When I click this button, it does all the fetch work (not illustrated above) creates the text file and downloads it... excellent...
Except, at the bottom of the JS file it downloads myJavascript.js it has all the markup from the page in which the button was.
I was under the impression that Response.ClearContent() should remove all this?
What am I doing wrong? Or does this have to be a separate page?
In case anyone else comes across this issue again, I solved the problem, very simple!
All it needed was
Response.End()
At the end!
So the full function becomes:
Sub Download() Handles button.click
var AllTheScript as string ="blah blah blah"
Response.Buffer = True
Response.Clear()
Response.ClearContent()
Response.Write(AllTheScript)
Response.ContentType = "application/text"
Response.AddHeader("content-disposition", "attachment; filename=myJavascript.js")
Response.Flush()
Response.End() '///<<< Final Line Essential!
End Sub
Try this
var context = HttpContext.Current;
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
////
context.Response.AddHeader("content-disposition", "attachment; filename=myJavascript.js");
content.Response.Write(AllTheScript);

set default name to PDF document with itextsharp

i am sending a PDF to my page and i want to set a default name when the user tries to save the PDF document.
i am using ItextSharp and VB.Net
Using s As MemoryStream = New MemoryStream()
Dim Pdf_Writer As PdfWriter = PdfWriter.GetInstance(DocumentPDF, s)
DocumentPDF.Open()
DocumentPDF.SetMargins(10.0F, 10.0F, 10.0F, 10.0F)
DocumentPDF.Add(Table)
DocumentPDF.Close()
contentX= s.ToArray()
HttpContext.Current.Response.Buffer = False
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ContentType = "Application/pdf"
HttpContext.Current.Response.BinaryWrite(contentX)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
End Using
.
Response.AddHeader("content-disposition", #"attachment;filename=""MyFile.pdf""");
this way download the file(yea, it sets a default name), but i just want to show the file and if the user wants to save it, well... save it(with a default name)
how can i set a default name to my PDF document?
try with this code:
Response.ContentType = "application/pdf"
Response.AppendHeader("Content-Disposition", "inline; filename="filename".pdf")
Response.TransmitFile("filename")
Response.End()
I had a similar problem delivering a PDF via a handler page (.ashx). No matter what I set in the HTTP headers, saving from the browser PDF reader would always set the filename to "getpdf.pdf" when I used this url.
http://www.thepdfchef.com/handlers/getpdf.ashx?id=5188p
So what I did was add an escaped string after the handler path then the querystring at the end of that, like so:
http://www.thepdfchef.com/handlers/getpdf.ashx/Wellbeing%20And%20Domestic%20Assistance%20From%20John%20Paul?id=5188p
You should check for invalid characters and strip out any that could cause the name to be dangerous.

saving dataset in excel and allow user to download it in the client machine

I am developing an application where i want i am displaying a dataset in the datagrid view for the user.Now the user wants to download the data in the datagridview in an excel format.How can i do it ?
1) should i write the dataset in the excel and save it the server before the user download the file ?
2) Can i use a hyper link and set the path of the file that is saved in the server to the hyper link hRef property , so that the user can click and download the file ?
I am using C# ASP.net 2.0
Please help !
no need to save the file to the sever use the following code, will create the file on the fly:
Public Shared Sub DataTableToExcel(ByVal dt As DataTable, ByVal FileName As String
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Write(Environment.NewLine)
For Each row As DataRow In dt.Rows
For i As Integer = 0 To dt.Columns.Count - 1
HttpContext.Current.Response.Write(row(i).ToString().Replace(";", String.Empty) + ";")
Next
HttpContext.Current.Response.Write(Environment.NewLine)
Next
HttpContext.Current.Response.ContentType = "application/ms-excel"
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls")
HttpContext.Current.Response.[End]()
End Sub
you can use this simple code to accomplish
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=SummaryReport" + DateTime.Now.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
grd.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
SpreadsheetGear for .NET will do it.
You can see ASP.NET (C# and VB) samples here and download a free trial here.
Disclaimer: I own SpreadsheetGear LLC

Resources