how to download an excel file from aspx webpage - c#

I am trying to fetch an excel file stored in bytes from database from an aspx webpage and download and open in .xls format, however the file is getting downloaded as .aspx . How to resolve this?
I tried:
private void download(DataTable dt)
{
if (dt.Rows.Count > 0)
{
Byte[] bytes = (Byte[])dt.Rows[0]["xyz"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.BinaryWrite(bytes);
// Response.Flush();
Response.End();
}
}

You need to set the Content-Disposition header. For example:
Content-Disposition: attachment; filename=your-excel-file.xlsx
And in code:
Response.AddHeader("Content-Disposition", "attachment; filename=your-excel-file.xlsx");

Related

excel cannot open the file because the file format or file extension is not valid c#

I am trying to download an excel file which for which I am giving the proper path. But after downloading it when I am trying to open I get error as
excel cannot open the file because the file format or file extension is not valid. Verify that file has been corrupted...
But If I open that file directly it gets open, I don't understand what is the issue in it. Below is my code
protected void MultipleSpanLinkIdDownLoadbtn_Click(object sender, EventArgs e)
{
try
{
string fileName = "multiSpanLinkeid.xlsx";
FileInfo file = new FileInfo(System.Configuration.ConfigurationManager.AppSettings["MultipleSpanLinkFolder"].ToString() + "/" + fileName);
if (file.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.AddHeader("Content-Type", "application/Excel");
Response.ContentType = "application/vnd.xls";
Response.AddHeader("Content-Length", file.Length.ToString());
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
catch (Exception)
{
ClientScript.RegisterStartupScript(this.GetType(), "Exception", "alert('Template downloaded.');", true);
}
}
Please suggest what is wrong in this
NOTE: The issue arises while downloading it from Chrome
Please try with this content type.
Response.ContentType = "application/vnd.ms-excel";
or
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Try this:
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

How to add password to Excel file generated from Report Server using c#?

I'm able to download excel through report server.I tried using EpPlus but i was not able to use it with report viewer. I want to add password to the excel file.
public static void SendFileBytes(HttpResponse response, byte[] fileBytes, string fileName, string mimeType)
{
if (response != null && fileBytes != null && fileBytes.Length > 0 && !String.IsNullOrWhiteSpace(fileName) && !String.IsNullOrWhiteSpace(mimeType))
{
response.Clear();
response.Buffer = true;
response.ContentEncoding = System.Text.Encoding.UTF8;
response.ContentType = mimeType; // "application/pdf";
response.AddHeader("content-disposition", "attachment;filename=" + Uri.EscapeDataString(fileName));
response.Charset = "";
response.Cache.SetCacheability(HttpCacheability.NoCache);
using (BinaryWriter bw = new BinaryWriter(response.OutputStream))
{
bw.Write(fileBytes);
bw.Close();
}
response.Flush();
response.End();
Did you try to use Microsoft.Office.Interop.Excel
Link reference Password Protecting an Excel file in C#

Byte array not writing to pdf stream c#

I've have a byte array that has all the data needed and can be displayed in a pdf that can be opened if I use this code:
System.IO.File.WriteAllBytes(#"C:\Users\Person\Downloads\results.pdf", bytes)
That let's me know the byte array should be good. The issue is I'm trying to create a pdf on the fly and when I view the call in the network tab in dev tools, it shows a 200 and in the response tab I get a text response. When I copy that response in a text editor and save it as a pdf, it has the correct amount of pages, but no data in it. So I have two issues here. For some reason, it is not being returned as a pdf AND the byte array is not being written to it. Any suggestions on what I can do? I've looked at stack overflow all day and have tried all kinds of things including setting the contentType to application/pdf.
byte[] bytes = ms.ToArray();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Buffer = true;
response.AddHeader("Accept-Header", bytes.Length.ToString());
response.AddHeader("Content-Length", bytes.Length.ToString());
response.AddHeader("Content-Disposition", "attachment;filename=Results.pdf");
response.AddHeader("Content-Description", "File Download");
response.ContentType = "application/octet-stream";
response.OutputStream.Write(bytes, 0, onvert.ToInt32(bytes.Length));
//I've tried using this as well
//response.BinaryWrite(bytes);
response.Flush();
response.End();
UPDATED CODE:
byte[] bytes = ms.ToArray();
HttpResponse response = HttpContext.Current.Response;
try
{
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("Accept-Header", bytes.Length.ToString());
response.AddHeader("Content-Length", bytes.Length.ToString());
response.AddHeader("Content-Disposition", "attachment;filename=Results.pdf");
response.ContentType = "application/pdf";
response.BinaryWrite(bytes);
response.Flush();
}
catch { }
finally
{
response.End();
}
I got it working with this:
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.ContentType = "application/pdf";
response.AddHeader("content-disposition", "attachment; filename=Results.pdf");
response.BinaryWrite(bytes);
response.Flush();
response.Close();

Binary to File download - But the downloaded file has no file extension?

protected void getFileAttachment(byte[] bytes)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = fileType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + "test101");
Response.OutputStream.Write(bytes,0,bytes.Length);
Response.BinaryWrite(bytes);
Response.Flush();
}
I'm trying to convert varbinary that is saved in SQL Server and I'm having trouble because the output file has no extension
Response.AppendHeader("Content-Disposition", "attachment; filename=" + "test101.filetype");
My fault - I did not include the file extension in my database
Thanks for the comments!

Convert .aspx page to Microsoft Excel Page

HI i want to use such thing in my web application that on a button click .aspx page converted in Xls page.
I did it but result is not good as I needed. I used this code on button click which is given below.
Response.Clear();
Response.Buffer = true;
string filename = "TicketSecretary.xlxs";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
I'm missing the Response.End(); at the end.
http://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx

Categories