Zipping an ExcelPackage in vb.net - asp.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()

Related

How to get the contents a particular cell using excel data reader in Visual Basic? Using ExcelData Reader

I'm using the following code and I'm trying to understand how to access the content of each cell in the excel document in order to Validate it... but everything that I've found on the internet is in C# I tried to translate it but I'm getting some errors.. this is my code:
Using stream = File.Open(FullUpldPath, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(stream)
Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New
ExcelDataTableConfiguration() With {
.UseHeaderRow = True}})
Dim tables As DataTableCollection = result.Tables
End Using
End Using
Dim file__1 as String = "excelpath"
If file__1.EndsWith(".xlsx") Then
' Reading from a binary Excel file (format; *.xlsx)
Dim stream As FileStream = File.Open(file__1, FileMode.Open, FileAccess.Read)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream)
excelReader.IsFirstRowAsColumnNames = True
dtExcelData = excelReader.AsDataSet()
excelReader.Close()
Return dtExcelData
End If
If file__1.EndsWith(".xls") Then
' Reading from a binary Excel file ('97-2003 format; *.xls)
Dim stream As FileStream = File.Open(file__1, FileMode.Open, FileAccess.Read)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream)
dtExcelData = excelReader.AsDataSet()
excelReader.Close()
Return dtExcelData
End If

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

How to Edit Excel with EPPLUS and send it as attachment

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.

Merging Jpg file to Pdf Stream

Here is my issue: I'm trying to read JPG files from a folder and convert them to one PDF file for example if in my folder I have 1).Hello.jpg 2). World.jpg I want to grab those files and combined it to a one PDF file so the result will be
newPDF.pdf
I'm reading the images correctly from the folder adding them to the document but it's not creating the new PDF file in the folder. How can I solve this??
Here is my code:
'!=Orginally after setting all the files in the folder we need to read the path from the session file.
'!= After reading the path we need to read each file from the folder and generate one pdf file.
Dim attachmentsFolder As String = "E:/IRAttachments/PSC/2013/2/IR-7264"
Dim fileName As String = String.Concat("IR_7264(", DateTime.Now.ToString("yyyyMMddHHmmssfff").ToString(), ").pdf")
Dim finalPathName As String = String.Concat(attachmentsFolder, "/", fileName)
'!= Step 2). read the pdf/images from folder and merge them to a one pdf file.
Dim files As New List(Of String)()
Dim readerList As New List(Of PdfReader)()
m_HashTableIRAttachments = New Hashtable
m_DictionaryEntryIRAttachments = New DictionaryEntry
Dim fileExtentionType As String = String.Empty
Dim doc As Document = New Document
For Each filePath As String In Directory.GetFiles(attachmentsFolder)
fileExtentionType = filePath.Substring(filePath.LastIndexOf("."))
If fileExtentionType = ".jpg" Then '# Get the extension type
Dim document As New Document()
Using stream = New FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)
PdfWriter.GetInstance(document, stream)
document.Open()
Using imageStream = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim image__1 = Image.GetInstance(imageStream)
document.Add(image__1)
Dim pdfFile As String = finalPathName
End Using
document.Close()
End Using
'PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + fileName, FileMode.Create))
'doc.Open()
'doc.Add(New Paragraph("Hello World"))
'Dim myDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
'Dim pdfFile As String = finalPathName
'Dim writer As PdfWriter = PdfWriter.GetInstance(myDoc, New FileStream(pdfFile, FileMode.Create))
'myDoc.Open()
'Dim para As New Paragraph("Let's write some text before inserting image.")
'Dim myImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(filePath)
'myImage.ScaleToFit(300.0F, 250.0F)
'myImage.SpacingBefore = 50.0F
'myImage.SpacingAfter = 10.0F
'myImage.Alignment = Element.ALIGN_CENTER
'myDoc.Add(para)
'myDoc.Add(myImage)
'myDoc.Close()
'doc.Close()
Else
'# Means it's a pdf and not a jpg file.
Dim pdfReader1 As New PdfReader(filePath)
readerList.Add(pdfReader1)
End If
Next
When you create the Stream for your PDF file, you are using the fileName variable, which is only the name, not the full path. It is likely that the PDF is being created - just not where you are expecting it to be. You probably want to use finalPathName instead:
Using stream = New FileStream(finalPathName, FileMode.Create, FileAccess.Write, FileShare.None)
I would also recommend you take a look at the methods available on the System.IO.Path class, and use them when constructing file paths and getting the file extension, e.g.
Dim finalPathName As String = Path.Combine(attachmentsFolder, fileName)
'...
fileExtentionType = Path.GetExtension(filePath)
' etc.
EDIT
It looks like you are also overwriting the PDF file for each image file, while I would imagine you want all of the images in one PDF file. Your loop for the images should probably be inside the Using stream = ... block (e.g. between document.Open() and document.Close()).

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.

Resources