asp.net reload page after export to excel - asp.net

I have a page which exports a document to excel on button click. What I need to do is refresh the page after the excel document has been sent.
I am trying to register a script which will cause a page refresh but cant get it to register at the same time as exporting to excel.
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "test", "alert('Done');", True)
Response.Clear()
Response.ClearHeaders()
Response.AddHeader("Refresh", "3; url=" + Request.RawUrl)
Response.ContentType = strMimeType
Response.AddHeader("content-disposition", "attachment; filename=CompleteReport." + strFilenameExtension)
Response.BinaryWrite(bytFileContent)
Response.End()

You can make
only one response for each requests
(first excel export, and the second would be the refresh).
After first response.end, you can't do anything.
You have to solve the excel export another way, with component etc.
And after export you can call
Response.redirect("your page");

Basically this can not be done if you want it reloaded only after the file has downloaded as it it not possible to find out when that is. Also you are clearing the response out and then writing the excel so the script isn't even returned from the server. The refresh-header is not being used by the browser when downloading a file either.
What you can do is to use the aspx-page to include a script like:
function onclick() {
window.location.href = 'loadmyfile.ashx?parameters...';
refreshPage();
}
The above will however refresh the page immediately on click so that might not be what you are after.

Related

Generating and downloading an `Excel` document breaks `ASP.net` LoginStatus

In my ASP.net web application I have a page which shows a (not very complicated) table. I have implemented a button so when the (registered) members clicks on it, the browser downloads the table as an Excel document
The code to generate this Excel is as follow:
Dim response As HttpResponse = HttpContext.Current.Response
' first let's clean up the response.object
response.Clear()
response.Charset = ""
Dim filename As String = MapPath("~/ex1.xls")
' set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """")
' create a string writer
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
' instantiate a datagrid
Dim dg As New DataGrid()
dg.DataSource = dt
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.[End]()
End Using
End Using
The problem is that this code is breaking somehow the ASPN.net LoginStatus as when you try to log out after downloading this Excel (the "log out" buttom is always visible at the application) every click on the buttom will download the same Excelover and over (once per click). If you reload window or change page the "log out" will work again.
this is the "log out" link when inspecting it with chrome:
<a id="ctl00_ctl00_MainContent_LoginStatus1" href="javascript:__doPostBack('ctl00$ctl00$MainContent$LoginStatus1$ctl00','')">Log Out</a>
I have tried to make the Excel to download from other page using:
onclick="window.document.forms[0].target='_blank';"
and now it opens a new tab, download the Excel, close the tab (fast process) but still keeps breaking the logout link.
And I run out of ideas, any help, code, hint or whatever possible solution to fix this problem is very welcome.
Open a new page within the blank target, and let the new page generate the excel
This looks like a server side error.
Your code to logout actually runs the code to download Excel.
May be you should throw in a 'Response.End();' in the click handler for logout.
Well a quick work around would be to use report viewer control, which has an export to excel functionality.
I know this solution is not exactly what you were looking for, but from my experience when a user is looking for excel functionality, instead of providing a table/gridview results to the user i provide an rdlc report, which has all the export functionality.

No response in postback after writing binary to the response

Requirement:
I want to download a file (*.docx) on the click of a button, first I read the bytes of the file, then I write the bytes to the response, this works fine and I have used this code several times before, but I am getting this weird behavior where the code executes successfully, without exceptions, but there is no response being sent back to the client (nothing happens, no response, no file download), furthermore, if I put the code in Page_Load event, the code works flawlessly, it only does not work in the button click event(i.e. on postbacks), here is the code that I am using:
Dim arrBytes() = File.ReadAllBytes(strFilePath)
Response.ClearHeaders()
Response.ContentType = "application/octet-stream"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=test.docx")
Response.AddHeader("Content-Length", arrBytes.Length.ToString())
Response.BinaryWrite(arrBytes)
Response.Flush()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Any help is much appreciated.
EDIT:
I tried 'Response.WriteFile instead ofResponse.BinaryWrite and Response.End instead of ApplicationInstance.CompleteRequest but nothing succeeded.
Turns out there was an UpdatePanel in the MasterPage, the problem was solved when I registered the button as a post back control ... That hurts I know.
So I solved it by using this line of code in the Page_Load event:
ScriptManager.GetCurrent(Me).RegisterPostBackControl(btnSubmit)

Output XML as file in ASP.NET

I'm having difficulty sending an XML stream to the client browser. I've researched this considerably and everything looks right - moreover, similar code works in a previous version of this app. Any ideas what I could be doing wrong?
The following code throws no errors, but does not download a file on the client machine.
Public Shared Sub Export(ByVal source As DataTable)
Try
With Current.Response
Dim xml As String = CreateExcelXMLFromDataTable(source.DefaultView)
.Clear()
.Buffer = True
.ContentType = "application/vnd.ms-excel"
.AddHeader("Content-Disposition", String.Concat("attachment;filename=", "export.xlsx", ";"))
.AddHeader("Content-Length", xml.Length.ToString)
.Charset = ""
.Write(xml)
.Flush()
.Close()
End With
Catch ex As Exception
Console.WriteLine(ex.Message.ToString)
End Try
End Sub
Thanks!
If you are calling this function in an Ajax request it will not work. You have to cause a full postback to send the file to the client.
You can send the file without causing a full postback in the current page using an popup window (window.open) or an iframe with the URL of the download asp.net page, which will call the Export function.

PDF from content of asp.net page

I'm trying to create a pdf of the content on a page ("returnsPage.aspx?id="returnId) and allow the user to download this directly when clicking the button.
However in my onClick method I have the following code:
lnkLoadPDF.CommandArgument = "/returns/returnsPage.aspx?id="+returnId.ToString();
string virtualPath = lnkLoadPDF.CommandArgument;
string fileName = System.IO.Path.GetFileName(virtualPath);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.WriteFile(virtualPath);
Response.ContentType = "";
Response.End();
Response.Redirect("/returns/returnsPage.aspx?id="+returnId);
which returns this error:
'/returns/returnsPage.aspx?id=23' is not a valid virtual path.
Can anyone please tell me what I'm doing wrong?
Thanks!
In order to turn a webpage into a pdf, you must convert it to pdf on the server. In order to do that, you must have a program on the server that can do that for you.
I've tried a variety of webpage-to-pdf converters and one of the better ones is a free, open source program called wkhtmltopdf.
After you create the pdf, you can either redirect the user to the newly created pdf (discouraged), or prompt them to download it with a savefile dialog.
If you get stuck, just search for wkhtmltopdf on stackoverflow or post another question.
You can't send a file to the client and redirect him to a new location during the same request. You also can't create a PDF from a webpage without some kind of component that converts the HTML into a PDF, it's (quite a bit) more tricky that what I think you're trying to attempt.
As for your exception, are you sure returnsPage.aspx exists? :)

How to download file and reload

I have a page which contains a button that perform the following code, I want to reload the page after the response end so that update a grid in that page. or suggest a way to update the grid after response end.
string report = new BLL.OrderReport.OrderReport().GenerateFullfilmentReport(fromdate, toDate
, string.IsNullOrEmpty(generationId)? null : ((int?)int.Parse(generationId)) );
if (!string.IsNullOrEmpty(report))
{
LoadReportHistory();
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=Report.text");
Response.Write(report);
Response.End();
}
Thanks
I work around this, the problem is that I need the Grid to be rebind after Response.End is called.
The target is updating the Grid when user click download. To work this out I rebind the grid first, and register a java script code to cause reloading the page (post back event will be resent),
in the second round I download the file.
I control this miss by copying the original file to temp file, then delete the temp file during first round, if the file exist then download.
Someone tell me something better please

Resources