How to Edit Excel with EPPLUS and send it as attachment - asp.net

i have the following code, which it is working, it opens a file stream from an embedded Xlsx saves it on a memorystream then pass the value to the attachment and send it with no problem.
Private Sub SendFile2()
Dim path As String = Server.MapPath("~/App_Data/RQM.xlsx")
Using fileST As FileStream = IO.File.OpenRead(path)
Dim memStream As New MemoryStream()
memStream.SetLength(fileST.Length)
fileST.Read(memStream.GetBuffer(), 0, CInt(fileST.Length))
'' Code for MailMessage and SMTP goes here
MailMsg.Attachments.Add(New Attachment(memStream, "myFile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
End Using
End Using
End Sub
Now im trying to do some edition (adding some values to that file, but still working in a memorystream) but i am having some problems
i've added
Using pck As ExcelPackage = New ExcelPackage(memStream)
Dim xlswb As ExcelWorkbook = pck.Workbook
Dim xlsws As ExcelWorksheet = xlswb.Worksheets.First
xlsws.Cells(20, 4).Value = "HELLO WORLD"
pck.SaveAs(memStream)
End Using
Which when i put breakpoints i see pck getting the value of MemStream with a lenght of 83084 (the value of the original file) 81kb xlsx, when i add the value to the cell the lenght of memStream is 162143 so it seems it does some modifications, however when i send again the memstream trough
MailMsg.Attachments.Add(New Attachment(memStream, "myFile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
i receive a file of 165b, and i'm not sure what i am doing wrong.
Any help would be apreciated
Edit:
Well i wasn't able to save it with the same memStream so instead i did this.
memStream2 = New MemoryStream(pck.GetAsByteArray())
MailMsg.Attachments.Add(New Attachment(memStream2, "myFile2.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
And that worked as a charm. Hope is useful to anyone.

Related

Download stream to file

I have a service which provides a stream. This stream should be written to a pdf-file.
I tried this method but it didn't work:
Using hcwHandler As IHealthCareWorkerServiceHandler = Container.CurrentContainer.Resolve(Of IHealthCareWorkerServiceHandler)()
stream = hcwHandler.DownloadPrescription(New DownloadPrescriptionRequest With {
.ProfessionCode = ucSelectProfession.ProfessionCode,
.RizivNumber = ucSelectProfession.Nihdi,
.Culture = language
}).Result
End Using
Dim buffer As Byte() = Encoding.ASCII.GetBytes(stream.ToString())
Using ms As New MemoryStream(buffer)
'write to file
Using file As New FileStream("prescription.pdf", FileMode.Create, FileAccess.Write)
ms.WriteTo(file)
End Using
End Using
I have tried several other solutions as well, but none seemed to work.
I never get a file.
Can anyone help me?
You can read the buffer (if there is data there) in a Using block without MemoryStream (like code below shows) and put a full absolute path like C:\Documents\PdfFolder\prescription.pdf
Using saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.InitialDirectory = "C:\Documents"
saveFileDialog1.RestoreDirectory = True
saveFileDialog1.Filter = "PDF files|*.pdf" ' change here for csv or xls
saveFileDialog1.FileName = "yourDefaultfileName.pdf"
If saveFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
If Len(saveFileDialog1.FileName.Length) > 0 Then
Try
Dim pdfPath As String = System.IO.Path.GetFullPath(saveFileDialog1.FileName)
Using file As New FileStream(pdfPath, FileMode.Create, FileAccess.Write)
file.Write(buffer, 0, buffer.Length)
End Using
MessageBox.Show("Saved in " & pdfPath)
Catch
MsgBox("Not a valid name file.")
End Try
End If
End If
End Using
And here a VB.NET version of How do I save a stream to a file in C#
Using fromWebFileStream As Stream = New StreamReader(yourStreamHere)
Using localFileStream As FileStream = File.Create("C:\Documents\PathTo\File")
'if you aren't at the begin of your stream uncomment this
'fromWebFileStream.Seek(0, SeekOrigin.Begin)
fromWebFileStream.CopyTo(localFileStream)
End Using
End Using

Zipping an ExcelPackage in vb.net

I have created an excel document in code and I'm trying to zip the file using ZipArchive. I was attempting to do this by using BinaryReader/Writers but the the stream that I tried to make doesn't seem to contain anything. Any ideas what I'm doing wrong?
Using zip As ZipArchive = New ZipArchive(MemoryStream, ZipArchiveMode.Create, True)
Dim excelFile As ZipArchiveEntry = zip.CreateEntry("QueryExportTest.xlsx")
Using writer As BinaryWriter = New BinaryWriter(excelFile.Open())
Dim excelReader As BinaryReader = New BinaryReader(excel.Stream())
While excelReader.PeekChar() <> -1
writer.Write(excelReader.ReadBoolean)
End While
End Using
End Using
excel was defined earlier with Dim excel As New ExcelPackage()

vb.net Word Document Replace Strings Images

I am trying to create mail merge process with word document (images, text, html). I am finding help online for a desktop application, but trying to do it from a web aspx page.
here is code I tried
Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True)
Using (wordDoc)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(wordDoc.MainDocumentPart.GetStream)
Using (sr)
docText = sr.ReadToEnd
End Using
Dim regexText As Regex = New Regex("Hello world!")
docText = regexText.Replace(docText, "Hi Everyone!")
Dim sw As StreamWriter = New StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))
Using (sw)
sw.Write(docText)
End Using
End Using
but can not even run. I get an error in visual studio 2015.
Severity Code Description Project File Line Suppression State
Error BC30002 Type 'WordprocessingDocument' is not defined.
Any ideas?
thanks

save excel using EPPlus

could someone help me with this error??
I tried to save excel file using EPPlus
[IOException: The process cannot access the file 'C:\Users\Julian\Downloads\EmployeeMaster.xls' because it is being used by another process.]
here is my code :
Dim conn As New ConnectionVB
Dim newfile As FileInfo = NewFileInfo("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Using p As ExcelPackage = New ExcelPackage(newfile)
SetWorkBookProperties(p)
conn.connect()
Dim ws As ExcelWorksheet = CreateSheet(p, "EmnployeeMaster")
Dim dt As New DataTable
Dim connString As String
connString = "Select * from EmployeeMaster"
dt = conn.openDataTable(connString)
Dim rowIndex As Integer
rowIndex = 2
CreateHeader(ws, rowIndex, dt)
CreateData(ws, rowIndex, dt)
Dim bin As Byte()
bin = p.GetAsByteArray()
Dim path As String
path = "C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls"
File.Delete("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Dim stream As Stream = File.Create(path)
File.WriteAllBytes(path, bin) <- I got the error here
Start(path)
stream.Close()
End Using
Appriciate all help/advice with this error
Regards Siekh
As from your Error shows: EmployeeMaster.xls file is being used by another process.
Your code DryRun:
In your EmployeeMaster.xls file you make another new sheet name as EmnployeeMaster and then you create Header, and Data in this sheet.
problem arise when you write to file. you have to just save WorkSheet by doing .
because just open your .xls file with the help of EPPlusPackage and then by code Add your custom sheet in .xls file and just save.
p.Save(); // you need to save this temporary sheet.
Problems may be:
EPPLUS cannot open xls files, only xlsx files.
Why you delete File.
solution: you can rename and then move.
EPPlus hold your file when you instantiate object for ExcelPackage(with the same Path)
Two Problems:
EPPlus does not support xls files.
For debugging why the file is used, I recommend using SysInternal's "process explorer", you can find it here.

asp.net openxml open docx, change content and stream to user

My code is below. I'm trying to open a Word document with Open XML and change certain text. The document must then be send to the client where they can save it on their PC or Open it. It send a document to the client but it is blank. When I save my InMemory document it says the file cannot be open it must contain at least one root element. I'm using Visual STudio 2010 Express. Please help me. What is wrong with my code?
Dim fileName As String = "directory on server\doc.docx"
Dim myDocument As WordprocessingDocument = WordprocessingDocument.Open(fileName, True)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(myDocument.MainDocumentPart.GetStream)
docText = sr.ReadToEnd
sr.Close()
Dim regexText As Regex = New Regex("XXXCourtXXX")
docText = regexText.Replace(docText, "JOHANNESBURG")
Dim ms As New MemoryStream()
Dim sw As StreamWriter = New StreamWriter(ms)
sw.Write(docText)
myDocument.MainDocumentPart.FeedData(ms)
Dim mem = New MemoryStream()
myDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream)
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Response.AppendHeader("Content-Disposition", "attachment;filename=Notice.docx")
mem.Position = 0
mem.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
You're dimming a new memory stream mem, writing nothing to it and then copying it to the output stream. Remove all lines referencing your mem variable.

Resources