Open excel file in asp.net - c#

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

Related

Excel file does not open in browser

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");

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

Create OpenExcel and download it

I have this code for creating an Excel file and then sending it for download:
Stream stream = Stream.Null;
using (ExcelDocument doc = ExcelDocument.CreateWorkbook(stream))
{
ExcelWorksheet wsheet = doc.Workbook.Worksheets.Add("Assessment");
doc.EnsureStylesDefined();
// add some cells
}
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename=Assessment.xlsx;charset=utf-8;");
Response.BinaryWrite(Utilities.Utilities.ConvertFileToByteArray(stream));
Response.End();
When it gets to end of the using, I get this error :
File contains corrupted data.
If I save file to my disk it works fine.
where I went wrong?
I'm using this Component.
change first line to :
MemoryStream stream = new MemoryStream();
Also Change
Response.BinaryWrite(Utilities.Utilities.ConvertFileToByteArray(stream));
to
Response.BinaryWrite(stream.ToArray());

save the document created by docX into response and send it to user for downloading

I am trying to use the amazing DocX library on codeplex to create a word document.
when the user clicks a button, the document is created and I want to be able to send it to the user immediately via response.. I am doing something similar to this now:
Edited code based on suggestions
using (DocX Report = DocX.Create(string.Format("Report-{0}.doc", DateTime.Now.Ticks)))
{
Paragraph p = Report.InsertParagraph();
p.Append("Title").FontSize(30).Bold()
.Append("Sub title").FontSize(28)
.AppendLine()
.Append(DateTime.Now.Date)
;
MemoryStream ms = new MemoryStream();
Report.SaveAs(ms);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".docx\"");
Response.ContentType = "application/msword";
Response.Write(ms);
Response.End();
}
I have tried a few variations of this.. but I am not able to achieve what I want.. Looking at this answer I can possibly save the document on the server and open with io stream.. but I want to avoid that extra step (and then I need to delete the file too)
I don't see the point of creating a file for few milli seconds.. there has to be a way to save the contents and send them to response stream.. right?
How'd I go about it?
thanks..
EDIT: my current code either throws up cannot open file (Access denied) error If I am using file stream, OR downloads an empty document file without any content (sometimes, type of response is written to document)
This code gets me an MS word document with System.IO.MemoryStream as it's content..
Okay, here is the final working solution:
For some reason, DocX library doesn't want to save to Response.OutputStream directly, so I had to save it to memory stream and write the memory stream to response, like Neil & Daniel suggested. Here's what worked for me:
MemoryStream ms = new MemoryStream()
Report.SaveAs(ms);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".doc\");
Response.ContentType = "application/msword";
ms.WriteTo(Response.OutputStream);
Response.End();
This might be a bit late, but I found a way to get this working with FileStreamResult:
public FileStreamResult DownloadDocument()
{
using (DocX document = DocX.Create(#"Test.docx"))
{
// Insert a new Paragraphs.
Paragraph p = document.InsertParagraph();
p.Append("I am ").Append("bold").Bold()
.Append(" and I am ")
.Append("italic").Italic().Append(".")
.AppendLine("I am ")
.Append("Arial Black")
.Font(new FontFamily("Arial Black"))
.Append(" and I am not.")
.AppendLine("I am ")
.Append("BLUE").Color(Color.Blue)
.Append(" and I am")
.Append("Red").Color(Color.Red).Append(".");
var ms = new MemoryStream();
document.SaveAs(ms);
ms.Position = 0;
var file = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
{
FileDownloadName = string.Format("test_{0}.docx", DateTime.Now.ToString("ddMMyyyyHHmmss"))
};
return file;
}
}
The important bit is setting the Position of the memorystream back to 0, otherwise it appeared to be at the end, and the file was returning empty.
Try using a MemoryStream instead of a FileStream.
Your current code looks really wrong:
You are saving the report to the OutputStream of the current response and then clear that response (!)
When you do Report.SaveAs(response.OutputStream); - it already writes file contents to the output stream. You don't need to do Response.Write(response.OutputStream);
So you code should look like this:
...
Report.SaveAs(response.OutputStream);
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".doc\"");
Response.ContentType = "application/msword";
I think you've got things a little back to front and confused.
First off, clear the output, then add the headers, then write out the content.
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".doc\"");
Response.ContentType = "application/msword";
// This writes the document to the output stream.
Report.SaveAs(response.OutputStream);
Response.End();
Also , if your file is a docx format file, append .docx rather than .doc to your filename.

Categories

Resources