How can I load a byte array into excel? - asp.net

I have a btye array that I would like to load into excel. This will do this in vb.net with visual studio 2008.
How can I load the byte array into Excel via memory or with code?

Here is code, you can try:
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename="
& dt.Rows(0)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
Take a look at this very good article explaining every step. At the end of article you will find the code to get Byte array and then get the file
Save and Retrieve Files from SQL Server Database using ASP.Net

Related

Server displays an old version of an application created with VB.NET

I have created an application in VB.NET that is responsible for creating a PDF using iTextSharp. It is hosted on a Windows Web Server with IIS. But sometimes it happens that the version delivered by the server is an old one, it does not show the latest changes made to the structure of the PDF. To solve it, I must upload the version that I have on my PC back to the server. Although I have not made any changes to the source code and it is exactly the same as the one on the server. Every time I invoke the .aspx file I do it with a random value parameter to try to avoid the cache, but apparently it is not the solution. I also have the following statement in the code: Response.Cache.SetCacheability (HttpCacheability.NoCache) Thank you very much for any help you can give me.
Here is how I create PDF: I use a function to create PDF and return it into a MemoryStream :
SendOutPDF(CreatePDF("Title", nro), nro)
Public Function CreatePDF(ByVal Titulo As String, ByVal Numero As Integer) As System.IO.MemoryStream
Dim PDFData As MemoryStream = New MemoryStream
...
Dim pdfDoc As iTextSharp.text.Document
...
Dim pdfWrite As PdfWriter =
iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, PDFData)
...
Return PDFData
End Function
Protected Sub SendOutPDF(ByVal PDFData As System.IO.MemoryStream, ByVal num As Integer)
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/pdf"
Response.Charset = String.Empty
Response.AddHeader("content-disposition", "attachment;filename=" & num & ".pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.OutputStream.Write(PDFData.GetBuffer, 0, PDFData.GetBuffer.Length)
Response.OutputStream.Flush()
Response.OutputStream.Close()
Response.End()
End Sub

asp.net large file download out of memory exception

I'm trying to download a file with size greater than 50mb in an asp.net page. But it fails on our production server. It works on development and QA servers. I'm using the following code.
Response.Clear()
oBinaryReader = New System.IO.BinaryReader(System.IO.File.OpenRead(sDocPath))
lFileSize = Microsoft.VisualBasic.FileLen(sDocPath)
Response.AddHeader("Content-Disposition", "attachment;filename=" & sDownloadFileName)
Response.ContentType = "application/unknown"
Response.BinaryWrite(oBinaryReader.ReadBytes(lFileSize))
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Response.End()
The error I'm getting from the server is as below.
Page_Load System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.BinaryReader.ReadBytes(Int32 count)
at ExportDoc.Page_Load(Object sender, EventArgs e) in c:\sitename\ExportDoc.aspx.vb:line 87 Server Name
What is wrong with the code?
OutOfMemoryException commonly thrown when there is no available memory to perform such operation when handling both managed/unmanaged resources. Therefore, you need to use Using...End Using block wrapping around BinaryReader to guarantee immediate disposal of unmanaged resources after usage with IDisposable interface:
Response.Clear()
Using oBinaryReader As BinaryReader = New BinaryReader(File.OpenRead(sDocPath))
lFileSize = FileLen(sDocPath)
Response.AddHeader("Content-Disposition", "attachment;filename=" & sDownloadFileName)
Response.ContentType = "application/unknown"
Response.BinaryWrite(oBinaryReader.ReadBytes(lFileSize))
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Response.End()
End Using
Another common usage of BinaryReader is using FileStream and a byte buffer to control file reading mechanism:
Using FStream As FileStream = New FileStream(File.OpenRead(sDocPath))
lFileSize = CType(FStream.Length, Integer)
Dim Buffer() As Byte
Using oBinaryReader As BinaryReader = New BinaryReader(FStream)
Buffer = oBinaryReader.ReadBytes(lFileSize)
End Using
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment;filename=" & sDownloadFileName)
Response.ContentType = "application/unknown"
Response.BinaryWrite(Buffer)
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Response.End()
End Using
References:
VB.NET Using Statement (MSDN)
BinaryReader Class (MSDN)
I tried the below code and it resolved my issue, found the code idea from MSDN website.
Using iStream As System.IO.Stream = New System.IO.FileStream(sDocPath, System.IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
dataToRead = iStream.Length
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=" & filename)
While dataToRead > 0
If Response.IsClientConnected Then
length = iStream.Read(buffer, 0, bufferSize)
Response.OutputStream.Write(buffer, 0, length)
Response.Flush()
ReDim buffer(bufferSize)
dataToRead = dataToRead - length
Else
dataToRead = -1
End If
End While
HttpContext.Current.ApplicationInstance.CompleteRequest()
End Using

file deletion not working in asp.net vb

I am using following code for file deletion on server after downloading at client site.
The code is working from visual studio but NOT working when website is hosted even on the coding machine.
'To save the word file at temp location with unique name
Dim varDate As String = DateTime.Now.ToString("yyyyMMdd_hhmmss_fff")
Dim theFileName As String = Server.MapPath("~/Temp/Report_" & varDate & ".docx")
oWord.ActiveDocument.SaveAs(theFileName)
oWord.ActiveDocument.Close()
oWord.Quit()
Dim filefullname As System.IO.FileInfo = New System.IO.FileInfo(theFileName)
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=Observation_Report.docx")
Response.AddHeader("Content-Length", filefullname.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.WriteFile(filefullname.FullName)
Response.Flush()
System.IO.File.Delete(theFileName)
Response.End()

Convert excel file to byte array

I'm using ASP.net with VB codebehind.
I need to be able to convert an excel file created in code into a byte array in order to send it to the client. Without saving the file to the server.
this is how i created the excel document
Dim APP As Excel.Application = New Excel.Application
Dim missing As Object = System.Reflection.Missing.Value
Dim Workbook As Excel.Workbook = (APP.Workbooks.Add(missing))
Dim worksheet As Excel.Worksheet = Workbook.ActiveSheet
'..Fill cells in worksheet..
This is how i transmit it:
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.Cookies.Clear()
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.CacheControl = "private"
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8
Response.AppendHeader("Content-Length", filebytes.Length.ToString())
Response.AppendHeader("Pragma", "cache")
Response.AppendHeader("Expires", 60)
Response.AppendHeader("Conetnt-Disposition", "attachement; filename='MostIssuesByModelReport.xlsx'; size=" & filebytes.Length.ToString() & "; creation-date=" & Date.Now.ToString("R") & "; modification-date=" & Date.Now.ToString("R") & "; read-date=" & Date.Now.ToString("R"))
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'write to client
Response.BinaryWrite(filebytes)
Response.End()
I just need to get the content of Workbook into filebytes
EDIT:
After looking around a bit more I can now make it download a file, however this file does not use the filename specified in the above code, it uses the name of the asp server page that the user is on, it also has a .aspx extension..however if I force it to open in excel it is correct. Besides popping up saying the source may be corrupted. Why is this happening and how can I fix it?

Get blob from SQL and write to browser for download

ASP / .NET 3.5 & SQL Server 2005
I'm trying to download a blobbed PDF from our SQL database, then without physically writing the file anywhere, output the file and download to user with the "Save / Open".
The code processes through without throwing an Exception, but no download occurs.
To be honest I'm not certain how close this is to "working"... I've tried piecing together several different samples from various posts, being that nothing seems to match my particular situation.
Response.ClearContent()
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "attachment; filename=MY_DOWNLOAD.pdf")
Dim bufferSize As Integer = 100
Dim outByte(bufferSize - 1) As Byte
Dim strSql As String = "SELECT BlobData, BlobData FROM Attachment WHERE RecordID = " & CInt(Request.QueryString("pid").ToString)
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("SqlServer").ConnectionString)
connection.Open()
Dim scSql As SqlCommand = New SqlCommand(strSql, connection)
Dim sdrSql As SqlDataReader = scSql.ExecuteReader(CommandBehavior.SequentialAccess)
Do While sdrSql.Read
Dim startIndex As Long = 0
Dim retVal As Long = sdrSql.GetBytes(1, startIndex, outByte, 0, bufferSize)
Do While retVal = bufferSize
Response.BinaryWrite(outByte)
Response.Flush()
startIndex += bufferSize
retVal = sdrSql.GetBytes(1, startIndex, outByte, 0, bufferSize)
Loop
Response.BinaryWrite(outByte)
Response.Flush()
Response.End()
Loop
sdrSql.Close()
End Using
I would strongly recommend saving the files to a temporary location on disk, then letting Response.TransmitFile send the file for you.
The problem with the approach that you are using is that you will have two copies of each file in memory. If your files are 100MB each and you have 100 simultaneous users, this will result in 20GB of memory being used by your app.
Also, your current code will send at most one file to the user since you end the response within the SQL loop.
Finally, Response.End is no longer recommended since it causes problems in non-IE browsers. Instead, use Context.ApplicationInstance.CompleteRequest().
As pointed out in the comments, you should wrap the creation of the temp file and TransmitFile operation in a try/finally statement and delete the temp file in the finally portion. This will handle various exceptions (such as the end user getting disconnected part way through the transmission process) and ensure that you don't have a bunch of temp files stranded on your disk.
While I agree with competent_tech's answer above, if you still feel like you don't want to write the file to disk and want to fetch it, then convert it to byte array and stream it as a "Save As", then you could try the following (sorry it's C#, but you can convert it to VB.NET pretty easily):
byte[] byteArray = GetBytesFromSource();
Response.AddHeader("Content-Disposition", "attachment; filename=Test.pdf");
Response.AddHeader("Content-Length", byteArray.Length.ToString(CultureInfo.CurrentCulture));
Response.ContentType = "application/octet-stream";
Response.OutputStream.Write(byteArray, 0, byteArray.Length);
Response.Flush();
I just tested this and it works like a charm :)

Resources