Save Window at Excel Report in C# - c#

I have a working Excel Report code. Still, when I click the button the file goes directly to my download folder, without giving me the option to change its name or selecting where I want to save it.
Code is the following:
public void GetExcel()
{
var list = (IList<LeaseViewModel>)Session["currentList"];
var grd = new GridView { DataSource = list, AutoGenerateColumns = true };
grd.DataBind();
Response.ClearContent();
Response.AddHeader("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Response.AddHeader("content-disposition", "attachment;filename=Leases.xls");
Response.ContentType = "application/excel";
var swr = new StringWriter();
var tw = new HtmlTextWriter(swr);
grd.RenderControl(tw);
Response.Write(swr.ToString());
Response.Flush();
Response.End();
tw.Close();
swr.Close();
}
Can somebody please indicate what should I change in order to have the window popping?
Thanks a lot.

Thanks for everybody highlighting this is a browser-configuration issue.
I thought that once I have the definition of the default name in the code I could also define it to always ask what is the name I want. I tested in different browsers though, and fact is you were right, thanks for identifying it and noticing me.
Regarding the default name issue, here is how I solve it:
Before:
Response.AddHeader("content-disposition", "attachment;filename=Leases.xls");
After:
Response.AddHeader("content-disposition", "attachment;filename=" + Session["listName"] + "_Report.xls");
Now regardless the report I export, the name is always customized.
Hope it helps other newbies like me (:

Related

WebForm Server.Transfer - Variables are not being recorded in downloaded files

I'm using Server.Transfer and in the 2nd place I have a number of labels that are updated with a Request.Form["textbox_text"];
This all works really well, but the problem is I also want to write the content in that textbox to file
like a word document using this method
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=Word.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application / vnd.ms -word";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
htw.Write("<table><h2><b>[ Text ]</b></h2><br>" + TextBox_name.Text + "</table>");
Response.Write(sw.ToString());
Response.End();
But whenever I check the file it will not have anything written on it. I've even tried to save the value of a Request.Form to a static variable and then write that variable but without any success.
How are you using Server.Transfer()? Post that code, make sure you are using the overload that preserves the form values:
Server.Transfer("page.aspx", true);

C# Postback - set text on page after sending download

I have a form that on submit, downloads a generated csv file. I have an asp:Literal on the page as a placeholder for loading text:
<div id="loading-text">
<asp:Literal ID="litLoadingText" runat="server"></asp:Literal>
</div>
$("input[type=submit]").on("click", function() {
//$(".loading-modal").show();
$("#loading-text").html("Loading...");
});
and I'm trying to change the text after the download is complete to say "Done!" or just get removed:
Response.Clear();
Response.Buffer = true;
var fileName = !String.IsNullOrEmpty(txtFileName.Value) ? txtFileName.Value : "ContentExport";
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
litLoadingText.Text = "Done!";
}
but the text doesn't change. I'm pretty sure this is because of the downloading, where I'm doing Response.End() and whatnot, but I'm not sure how to handle it. Is there a way to do this in C#, or is there a Javascript method I could use instead to detect when the download is done? What would be the best approach?
The problem is described here: https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end-response-redir
Cause
The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.
This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.
Resolution
To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Executemethod instead.

Illegal characters in path c# error

I am getting the error
Illegal characters in path
for the code below . Please help me out.
response.Clear();
response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
string sFileName = "Testeeeeee.xls";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFileName + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = DS.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
string sPath = #"E:\CR-12\Test.xls";
File.WriteAllText(sw.ToString(), sPath);// I get the error at this line
response.End();
The parameters are inverted. Do it as follows:
File.WriteAllText(sPath,sw.ToString());
You've got the parameters to File.WriteAllText mixed up. The first one is the path, the second is the contents. You need
File.WriteAllText(sPath, sw.ToString());
The call to
File.WriteAllText(sw.ToString(), sPath);
has the wrong parameter order. It should be
File.WriteAllText(sPath, sw.ToString());
For others receiving this error, make sure you are using backslashes correctly since they are also escape characters. A single backslash can result in this error. Use 2 backslashes to properly output a single escaped backslash.
Ex:
System.IO.File.WriteAllText("C:\\file.txt", output);
The issue is probably a security related one. Your webpage wouldn't be default have access to the E drive.

Export All Rows of Paged ListView to Excel

In ASP.NET 4.0 webforms, I'm trying to export a paged ListView control to an Excel file by un-paging the ListView's (trucks) datasource:
dsTrucks.EnablePaging = false;
For a non-paged ListView control, I can get it to work.
Here's the attempt to "un-page" and then export the ListView control:
// Nuke the current page.
Response.Clear();
// Setup the response header.
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Trucks.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
// Turn off view state.
this.EnableViewState = false;
// Create a string writer.
var stringWriter = new StringWriter();
// Create an HTML text writer and give it a string writer to use.
var htmlTextWriter = new HtmlTextWriter(stringWriter);
// Disable paging so we get all rows.
dsTrucks.EnablePaging = false;
// Render the list view control into the HTML text writer.
listViewTrucks.DataBind();
listViewTrucks.RenderControl(htmlTextWriter);
// Grab the final HTML out of the string writer.
string output = stringWriter.ToString();
// Write the HTML output to the response, which in this case, is an Excel file.
Response.Write(output);
Response.End();
There's no error but the output in the Excel file is still just one page of the ListView control instead of all rows.
Any ideas on where to start to get this to work?
Thanks,
Adam
Just a guess, but it might be that EnablePaging works only on the control's OnInit() and it is too late by the time you call it from your code.
Perhaps you could you set the PageSize some MAXINT value and force all results into one single page?

Export HTML Table in asp.net MVC

I trying to export an HTML table named Table that is dynamically binded to ViewData.Model in C#. I have a method called export that is called based on another method's actions. so everything before that is set up.. I just don't know how to export the data to a CSV or Excel file.. So when the I step inside the Export method I don't know what next to do to export the table. Can someone help me
public void Export(List<data> List)
{
//the list is the rows that are checked and need to be exported
StringWriter sw = new StringWriter();
//I don't believe any of this syntax is right, but if they have Excel export to excel and if not export to csv "|" delimeted
for(int i=0; i<List.Count;i++)
{
sw.WriteLine(List[i].ID+ "|" + List[i].Date + "|" + List[i].Description);
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
I don't quite understand the whole "export an HTML table named Table that is dynamically binded to ViewData.Model" so I'll just ignore that and focus on your Export(List<data> list) method. Btw, you never really mentioned what was going wrong and where.
I see you had written "if they have Excel export to excel and if not export to csv" - I would personally just export it as a CSV file in both cases because excel can handle csv files no problem.
So with that in mind, here would be my export method based on your code.
public void Export(List<DataType> list)
{
StringWriter sw = new StringWriter();
//First line for column names
sw.WriteLine("\"ID\",\"Date\",\"Description\"");
foreach(DataType item in list)
{
sw.WriteLine(string.format("\"{0}\",\"{1}\",\"{2}\"",
item.ID,
item.Date,
item.Description));
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
This is an excellent example, but I think that need a globalization modification.
String ltListSeparator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
sw.WriteLine(string.format("{0}" + ltListSeparator + "{1}" + ltListSeparator + "{2}", item.ID, item.Date, item.Description));
I think your controller action method will need to wrap the data items in an html table which you may want to do any way you like, So your html+ data will be stored in a string and then you could do something like below- (its not exacly built for MVC but its easy to modify for it).
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
Response.Write(yourDataAndHtmlAsString);
Response.End();
CSV is a simple format and can be built up easily as a string.
http://en.wikipedia.org/wiki/Comma-separated_values
You could create an excel spreadsheet of what you think the end product should look like, save as CSV, open it in notepad and try and replicate it using a string builder.

Categories