save excel using EPPlus - asp.net

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.

Related

Rename file name based on upload date

I write the below code to copy the file and rename file name but the problem that i have now that i need to pick the last file (based on upload date) then rename the file , the below code change all files placed in the folder regardless the upload date , also if there is a simple code to upload file check if file is exist then show message (successful upload , failed upload (duplicate file))
Dim directory = Server.MapPath("App_Data/text/")
For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
Dim fName As String = IO.Path.GetFileName(filename)
If fName.ToString Like "*Cust*" Then
System.IO.File.Delete(Server.MapPath("App_Data\test\Customer.txt"))
My.Computer.FileSystem.CopyFile(Server.MapPath("App_Data\text\" & fName), Server.MapPath("App_Data\test\" & fName))
My.Computer.FileSystem.RenameFile(Server.MapPath("App_Data\test\" & fName), "Customer.txt")
you can use below code and find creation date and last modified date of a file:
Dim creation as DateTime = File.GetCreationTime(#"C:\test.txt")
Dim modification as DateTime = File.GetLastWriteTime(#"C:\test.txt")
or by Importing System.IO and using this code:
Dim fi as FileInfo = new FileInfo("path")
Dim created = fi.CreationTime
Dim lastmodified = fi.LastWriteTime
i think the second one is better because you can put them in a collection easily and then sort them or compare them.

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()

MS Access OLEDBConnection to Excel Issue

So I have searched for a about 2 days now and while I can find a lot of examples of how to get an Excel worksheet into a gridView, none of them work for me.
This is the goal: I need to read an Excel file, has one worksheet in it and should always be one worksheet in it, into a GridView in ASP.NET website and I am using VB.Net in code behind file.
I tried one way trying to use the Schema of the table name (To get the sheet names) but no matter what the sheet name was it always came back as 'Algrip' of which there is NO sheet with that name in any of the workbooks I an testing with.
So I scrapped that and am now using the this code: (Which does get the job done, sort of)
'Setup Variables
Dim xlConnStr As String = ""
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim FolderPath As String = ConfigurationManager.AppSettings("FolderPath")
Dim sheetname As String = InputBox("Enter Sheetname: ", "Excel Worksheet name")
'Adjust Sheetname
sheetname = sheetname + "$"
'Set Connection based on Excel File Extension
Select Case Extension
Case ".xls"
'Excel 97-03
xlConnStr = ConfigurationManager.ConnectionStrings("Excel03ConString").ConnectionString
Case ".xlsx"
'Excel 07-Forward
xlConnStr = ConfigurationManager.ConnectionStrings("Excel07ConString").ConnectionString
End Select
xlConnStr = String.Format(xlConnStr, FolderPath & FileName)
Dim connXL As New OleDb.OleDbConnection(xlConnStr)
pnlFileInfo.Visible = True
connXL.Open()
Using xlCmd As New OleDbCommand
xlCmd.CommandType = CommandType.Text
xlCmd.CommandText = ("Select * From [" + sheetname + "]")
xlCmd.Connection = connXL
Using xlDS As New DataSet()
Using xlDA As New OleDbDataAdapter(xlCmd)
xlDA.Fill(xlDS)
gvExcelFile.DataSource = xlDS
gvExcelFile.DataBind()
End Using
End Using
End Using
connXL.Close()
Now my problem is this; On the follwoing line:
xlCmd.CommandText = ("Select * From [" + sheetname + "]")
If I do not have the left and right brackets, because the some sheet names have spaces in them, I get a query error. But if I add the brackets it prompts me twice for the sheet name. For the life of me I can not figure out why.
I have put a break point in on the line listed above and checked the value of the variable sheetname and it is correct but for some reason I get prompted again.
Does anyone have any idea as to why it is doing this? What am I missing? What I ideally wanted was to be able to read the sheet name and feed it to the line with the select statement so that there is no user action required but all I ever got that way was the same bad sheet name 'Algrip'.
The Excel sheet is an xls file but can be saved as xlsx if it would help.
I am open to re-doing the code if i can get it to read the sheet name dynamically.
Thanks for any help!!
try storing the whole command in a variable then assign it to the xlCmd.CommandText using the OleDbCommand constructor
Dim sheetname As String = InputBox("Enter Sheetname: ", "Excel Worksheet name")
sheetname = sheetname & "$"
Dim strQuery As String = "Select * From [" & sheetname & "]"
...
Using xlCmd As New OleDbCommand(strQuery ,connXL)
Using xlDS As New DataSet()
Using xlDA As New OleDbDataAdapter(xlCmd)
xlDA.Fill(xlDS)
gvExcelFile.DataSource = xlDS
gvExcelFile.DataBind()
End Using
End Using
End Using
connXL.Close()

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.

Display a pdf file size value in a gridview in asp.net

My sql query is returning records from the database that contains a filename. I will be appending the filepath (from the web.config file) to allow the user to download the complete file. However, another colum in the grid, has to be the file size.
How can I obtain the filesize, given that the name is being returned from the database, and the filepath is from the web.config file?
Thanks
One way to do it is to store the size of the pdf file upon your upload of the file to the server and then just retrieve it along with the file name.
Using System.IO you can get the filesize
Dim f As New FileInfo("thefullfilepath")
Dim i As Integer = f.Length
EDIT: Use Import System.IO for VB
string MyFile = "~/files/my.pdf";
FileInfo finfo = new FileInfo(Server.MapPath(MyFile));
long FileInBytes = finfo.Length;
long FileInKB = finfo.Length / 1024;
Use the FileInfo class:
' Build the string fileName from path stored in Web.Config and the filename
' returned from the database
Dim fileName As String = "your path and filename"
Dim fInfo As FileInfo = new FileInfo(fileName)
Dim fileSize As Long = fInfo.Length
You will probably need to do this in the RowDataBound event, assuming your binding your GridView to a datasource (like your SQL query).

Resources