Excel file does not open in browser - c#

I am using aspose to find specific text and highlight it and open that excel file in browser.
Problem is it find and highlight and excel file get downloaded, which i dont want i want to show the contents of excel in browser.
For pdf this works perfectly fine, opens up in browser
PDF code -
if (docBytes != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", docBytes.Length.ToString());
Response.BinaryWrite(docBytes);
}
Here is my code - (excel) - Does not open excel in browser
using (MemoryStream docStream = new MemoryStream())
{
workbook.Save(docStream, Aspose.Cells.SaveFormat.Xlsx);
docBytes = docStream.ToArray();
}
if (docBytes != null)
{
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition",
"attachment; filename=" + "yourExcelFileName.xlsx");
Response.AddHeader("content-length", docBytes.Length.ToString());
Response.BinaryWrite(docBytes);
Response.End();
}

Look at these lines.
Response.AppendHeader("content-disposition",
"attachment; filename=" + "yourExcelFileName.xlsx");
The "attachment" part tells the browser that this file should be downloaded and not displayed in the browser.
Remove that and it should work (in browser that can host Excel at least, so Internet Explorer and possibly Edge).
Response.AppendHeader("content-disposition", "filename=yourExcelFileName.xlsx");
You can read about the attachment parameter over on MDN.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Syntax

I think you may try the line instead if it makes any difference:
Response.AppendHeader("content-disposition",
"inline; filename=" + "yourExcelFileName.xlsx");

Related

Response.TransmitFile() fails to transmit an empty file

I'm implementing a column in GridView to allow users to download files when they click on the file name(files are stored in Uploads folder of my Project).
Code is working fine when there's some data in the file i.e. user can click on file and it'll get downloaded but when a user clicks on a file which is empty (like an empty .docx file) a blank page is shown instead of downloading the file.
here's the code:
else if (e.CommandName == "Download")
{
Response.Clear();
if (File.Exists(Server.MapPath("~/Uploads/") + e.CommandArgument))
{
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument.ToString());
Response.TransmitFile(Server.MapPath("~/Uploads/") + e.CommandArgument);
Response.End();
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File Not Found";
}
}
I've tested on Chrome, Mozilla and IExplorer.
you need change this line:
Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument.ToString());
for this one:
Response.AppendHeader("Content-Disposition", filename=\"" + e.CommandArgument.ToString()) \"";

Download PDF file from a Directory Listing

I have used a Gridview Control to display the contents of a directory in asp.net webforms.
The contents are filtered to display only PDF files.
I also have a Button inside a TemplateField. On the click of the button the user should be able to download and save the PDF file.
The columns displayed in the Gridview are File Name, Modified Date and Size.
How can I program the Button click to download and save the PDF file?
I have a function that performs a file download.
public static void DownloadFile(string FilePath, System.Web.HttpResponse response)
{
System.IO.FileInfo file = new System.IO.FileInfo(FilePath);
if ((file.Exists))
{
response.Clear();
response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
response.AddHeader("Content-Length", file.Length.ToString());
response.ContentType = "application/octet-stream";
response.WriteFile(file.FullName);
response.End();
response.Close();
file = null;
}
}
The FilePath parameter is the physical path, so if you have the virtual path (e.g. ~/Folder/file.pdf) might need to use the Server.MapPath(...) function to call the function.
In your Button click event, write the following code.
protected void Button1_Click(object sender, EventArgs e)
{
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=Your_Pdf_File.pdf");
Response.TransmitFile(Server.MapPath("~/Files/Your_Pdf_File.pdf"));
Response.End();
}

Opening a document in PDF as opposed to Word with code on a button click

I have copied code previously used throughout the system i am working on. However this code opens the content in a word document. I am looking it to be opened in a PDF.
I have already tried changing the string declaration 'filename' to end in (.pdf) as opposed to (.doc) but when attempting to open it it says "could not open the document because it is either not a spported file type or because the file has been damaged....".
What changes need to be made to this code in order to open it as an adope pdf. I wouldnt imagine it would be alot.
string content = sw.GetStringBuilder().ToString();
string fileName = "IRPBestPracticeArticle.doc";
Response.AppendHeader("Content-Type", "application/msword; charset=utf-8");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Charset = "utf-8";
Response.Write(content);
I cannot say for certain, but I am going to assume you're trying to save your data as a pdf and have it open in whatever application the system uses to read pdf files?
//Note the change from application/msword to application/pdf
Response.AppendHeader("Content-Type", "application/pdf; charset=utf-8");
Make sure to change the mime type as well as the doc ending (See here for full list of mime types):
That being said, I cant guarantee it will open properly in your PDF reader
Just try this set of code.
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + fileName);
Response.ContentType = "application/pdf";
Response.WriteFile("FullFilePath");
Response.Flush();
Response.Clear();
Response.End();
The mime type need to be set correctly before opening the file.
Andy try this one. You must have ItextSharp.dll to use this code. Download it from here. Then add its reference in your page.
try this code to create pdf from string and download it
Document document = new Document(PageSize.A4);
using (MemoryStream ms = new MemoryStream())
{
PdfWriter.GetInstance(document, ms);
document.Open();
System.Xml.XmlTextReader _xmlr;
if (String.IsNullOrEmpty(errorMsg))
_xmlr = new System.Xml.XmlTextReader(new StringReader(GetTransferedData(content)));
else
_xmlr = new System.Xml.XmlTextReader(new StringReader(#"<html><body>Error Message:" + errorMsg + "</body></html>"));
iTextSharp.text.html.HtmlParser.Parse(document, _xmlr);
document.Close();
ms.Flush();
byte[] data = ms.ToArray();
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();
ms.Close();
}
First, convert the .doc files to PDF files. Here is a sample of how to achieve this: Convert Doc file to PDF in VB.Net
After you have the PDF files, stream them to the browser using the "application/pdf" content type.

Open document with word, without path

I'm searching how to open a document with word, without its path.
I get my document like this :
byte[] text = item.Doc;
The document comes directly from database.
I only found way to open with a path... So with my doc, I must open it, and then run saveAs of word application (choice between pdf, doc etc...).
I can store it in a MemoryStream, but, what can I do with it next?
Found this How to open a file from Memory Stream, but not helping me.
try this
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/ms-word";
string fileName = "Test.doc";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
StreamReader reader = new StreamReader(memoryStream, System.Text.Encoding.UTF8, true);
string strContents = reader.ReadToEnd();
Reader.Close();
Response.Write(strContents);
Response.End();
--SJ

Open excel file in asp.net

I am trying to open a Excel(.xls) file from asp.net.The code i am using is given here.It is showing a save as dialog box which i don't want .Please help me !!!
Response.ContentType = "application/xls";
Response.Flush();
Response.WriteFile(fileName);
Response.End();
Try adding response.addheader and use "binarywirte" instead of "writeFile" to your code like below sample code(working code) ...
System.IO.FileStream fs = null;
fs = System.IO.File.Open(filename, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + filename);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();
This is ultimately controlled through file associations in the operating system.You can modify registry settings on a per machine basis to achieve this result.
You would need to change the subkeys under HKEY_LOCAL_MACHINE\SOFTWARE\Classes that relate to excel. Specifically you have to add the following value:
Name=BrowserFlags; Type=REG_DWORD; Value=8

Categories

Resources