MS Access OLEDBConnection to Excel Issue - asp.net

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

Related

How to copy workbook (.aspx file) from html link to current workbook

I have trouble with the following tasks in excel VBA:
At my work, we use a document management platform called TeamShare: [https://www.lector.dk/en/products/]
I want to create a code in VBA, that loops over a range of links to this document management platform in my workbook, ie. loops over other workbooks, opens them and then copies a specified sheet to my current workbook.
I have tried putting together bits of codes from other sites, and the code works just fine when i run it in break mode. However, when I run the code all at once, the Excel program reopens, such that the current workbook cannot "communicate" with the opened workbook and I end up in an infinity loop (so no direct error message).
This is the code that only works in break mode:
Dim wbCopyTo As Workbook Dim wsCopyTo As Worksheet Dim i As Long Dim Count As Long Dim WBCount As Long Dim LastRow As Long Dim wb As Workbook Dim ws As Worksheet Dim URL As String Dim IE As Object Dim doc As Object Dim objElement As Object Dim objCollection As Object
Set wbCopyTo = ActiveWorkbook Set wsCopyTo = ActiveSheet
LastRow = wsCopyTo.Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
The purpose of this piece of code is to get the DocID
A = InStr(wsCopyTo.Range("B" & i), "documentid=") + Len("documentid=")
B = InStrRev(wsCopyTo.Range("B" & i), "&")
DocID = Mid(wsCopyTo.Range("B" & i), A, B - A)
'Get URL
URL = wsCopyTo.Range("B" & i)
'Count number of open workbooks
WBCount = Workbooks.Count
With IE
New is the comman that opens excel sheet. This works as planned in breakmode, however the excel program reopens when i run the code all at once. I have tried other commandos here: "Workbooks.Open", I couldn't get this one to open the file and "Application.FollowHyperlink" only worked in break mode too, however, much much slower
.Navigate URL
'This was my solution to how to stop the rest of the code from executing until the new workbook has loaded.
Do Until Workbooks.Count = WBCount + 1: Loop
End With
'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
'So in order to activate the workbook from the URL, I am looping over all my open workbooks and matching them on their unique Document ID. I found that the workbook from the URL wasn´t the "active workbook" per default.
For Each book In Workbooks If Mid(book.Name, 12, Len(DocID)) = DocID Then
book.Activate
Set wb = ActiveWorkbook
Set ws = ActiveSheet
End If
Next book
Here i copy the desired sheet to my initial workbook
wb.Worksheets("SpecificSheetIWantToCopy").Copy After:=wbCopyTo.Worksheets("Sheet1") wbCopyTo.Sheets(ActiveSheet.Name).Name = DocID
Next i
End Sub
I am using excel 2010.
I hope you can help me resolve this problem. Please ask if you need any more information, that i haven´t provided.
Thanks in advance.

Open XML SDK Open and Save not working

I am having trouble with the Open XML SDK opening and saving word documents.
I am using the following code (VB.Net):
Try
'Set Path
Dim openPath As String = "../Documents/" & worddoc
Dim savePath As String = "\\web-dev-1\HR_Documents\" & worddoc
Using doc As WordprocessingDocument = WordprocessingDocument.Open("/Documents/" & worddoc, True)
'Employee Name Insert
'Find first table in document
Dim tbl1 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row As TableRow = tbl1.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell As TableCell = row.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p As Paragraph = cell.Elements(Of Paragraph)().First()
Dim r As Run = p.Elements(Of Run)().First()
Dim txt As Text = r.Elements(Of Text)().First()
txt.Text = ddlEmployeeList.SelectedItem.Text
'Save File
'Supervisor Name Insert
'Find second table in document
Dim tbl2 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row2 As TableRow = tbl2.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell2 As TableCell = row2.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p2 As Paragraph = cell2.Elements(Of Paragraph)().First()
Dim r2 As Run = p2.Elements(Of Run)().First()
Dim txt2 As Text = r2.Elements(Of Text)().First()
txt2.Text = ddlSupervisorList.SelectedItem.Text
End Using
Return 1
Catch ex As Exception
Return Nothing
End Try
The trouble starts on the first using statement. It throws the following error:
Could not find a part of the path 'C:\Documents\Hourly_Employee_Performance_Review .docx
I have placed the word documents in a folder of the ASP.NET site called Documents. I also have created a public share on the dev server to see if maybe that would help.
The problem is that it doesn't use the supplied path variable. I have gone through the documentation for OPEN XMl SDK but all it talks about is the Using Statement and its need and use for it.
Can anyone tell me, show me, or point to a site that has examples of how to set both the open path and save path?
You need a path to the file which is based on the filesytem, not a URL. You can do that with
Dim openPath As String = Path.Combine(Server.MapPath("~/Documents"), worddoc)
And then to open the file:
Using doc As WordprocessingDocument = WordprocessingDocument.Open(openPath, True)
It appears that you will need to do the same for the location to save to, but you didn't say if "\\web-dev-1" is a different server; if it were that would need other considerations.
(Not tested, some typos may exist. You will need an Imports System.IO.)

VB Saving img file with path adds folder name to file name

Hi I am having some problems with saving img files using Visual Basic, the files are being named wrongly with the folder name being added to the start of the file name.
I parse a web address and then use the split address values to rename my files however the the path value seems to be added to the file as well.
The files in the photo should be named for example "DCAT040iMBE Test13.jpg"
but this file is being name "Test1DCAT040iMBE Test13.jpg"
Protected Sub GeneratedCode()
Dim path As String = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\"
LogoUpload.SaveAs(path + LogoUpload.FileName)
TextFile.SaveAs(path + TextFile.FileName)
Dim lines() As String = IO.File.ReadAllLines(path + TextFile.FileName)
For Each line As String In lines
Dim count As Integer
Dim encoder As New QRCodeEncoder()
encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H
encoder.QRCodeScale = 10
Dim img As Bitmap = encoder.Encode(line)
Dim logo As System.Drawing.Image = System.Drawing.Image.FromFile(path + LogoUpload.FileName)
Dim left As Integer = (img.Width / 2) - (logo.Width / 2)
Dim top As Integer = (img.Height / 2) - (logo.Height / 2)
Dim g As Graphics = Graphics.FromImage(img)
Dim parseLine = line
Dim replaceDelimiter As String
If Not String.IsNullOrWhiteSpace(line) Then
replaceDelimiter = Replace(line, "&", "=")
End If
Dim fileNameSplit() As String = replaceDelimiter.Split("=")
Dim newFileName As String
Dim partTwo = fileNameSplit(1)
Dim partSix = fileNameSplit(5)
Dim objFSO
Dim newFolder As String
newFolder = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\" + partSix
objFSO = CreateObject("Scripting.FileSystemObject")
If (Not System.IO.Directory.Exists(newFolder)) Then
System.IO.Directory.CreateDirectory(newFolder)
End If
count += 1
g.DrawImage(logo, New Point(left, top))
newFileName = partTwo & " " & partSix & count & ".jpg"
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
amountCreatedLbl.Text = count & " QRCodes Created"
logo.Dispose()
Next
End Sub
Could it be that I am generating my newFolder Values wrongly?
edited to add an example of data from the parsed txt file.
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test
Looks like you are missing a slash on the line:
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
It should be:
img.Save(newFolder + "\" + newFileName, ImageFormat.Jpeg)
The program doesn't realize that the newDirectory variable is supposed to be a directory, it's just being concatenated to the filename directly. A better option would be to use:
img.Save(System.IO.Path.Combine(newFolder, newFileName), ImageFormat.Jpeg)
The System.IO.Path.Combine() function automatically adds the missing slash between the directory and filename, as well as some additional checks to make sure the result is valid.
As a side note, I would also recommend using & instead of + when joining strings together. Hard to debug issues can come up when you do it that way. I would also recommend turning Option Strict On, you will see a couple of other warnings that come up with your code as is. But, to resolve your issue, the above will work.

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.

Reading CSV file with OLEDB ignores first line even with HDR=No in Connection String

We're converting a Classic ASP site to an ASP.NET site. One function was to upload a 'template' of data in CSV format for importing into the database. There were several different record types in there (the first field always indentifies the type of data).
The task was to get the CSV into a DataTable so it could be validated (new project is to have MUCH better validation rules)
The code seemed pretty straightforward - watered down (taking out comments, Try/Catch, etc) it is as follows:
Dim da As New System.Data.OleDb.OleDbDataAdapter
Dim cn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strDirectory & ";" & "Extended Properties=""Text;HDR=No;FMT=Delimited;""")
Dim cd As New System.Data.OleDb.OleDbCommand("SELECT * FROM " & strCSVFilename, cn)
cn.Open()
da.SelectCommand = cd
da.Fill(dtData)
The DataTable (dtData) is populated, but only starting with the second line of the CSV file DESPITE the fact that "HDR=No" is in the connection string.
What am I missing here?
Is there maybe something at the begining of the file that's causing the first row to be skipped? Maybe a non-printable character? The NPC could come from the file not being saved in an expected encoding. When I created a CSV file I received the results that you expected. Here's the code that I used to test:
Private Sub Test()
Dim TempDir = My.Computer.FileSystem.SpecialDirectories.Temp
Dim TempFile = "Test.csv"
'//Create our test file with a header row and three data rows
Using FS As New System.IO.FileStream(System.IO.Path.Combine(TempDir, TempFile), IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.Read)
Using SW As New System.IO.StreamWriter(FS, System.Text.Encoding.ASCII)
SW.WriteLine("Col1,Col2")
SW.WriteLine("R1", "R1")
SW.WriteLine("R2", "R2")
SW.WriteLine("R3", "R3")
End Using
End Using
'//Read the data into a table specifying that the first row should be treated as a header
Using dtData As New DataTable()
Using da As New System.Data.OleDb.OleDbDataAdapter
Using cn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & TempDir & ";" & "Extended Properties=""Text;HDR=Yes;FMT=Delimited;""")
Using cd As New System.Data.OleDb.OleDbCommand("SELECT * FROM " & TempFile, cn)
cn.Open()
da.SelectCommand = cd
da.Fill(dtData)
Trace.WriteLine("With header, expected 3, found " & dtData.Rows.Count)
End Using
End Using
End Using
End Using
'//Read the data into a table again, this time specifying that the there isn't a header row
Using dtData As New DataTable()
Using da As New System.Data.OleDb.OleDbDataAdapter
Using cn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & TempDir & ";" & "Extended Properties=""Text;HDR=No;FMT=Delimited;""")
Using cd As New System.Data.OleDb.OleDbCommand("SELECT * FROM " & TempFile, cn)
cn.Open()
da.SelectCommand = cd
da.Fill(dtData)
Trace.WriteLine("Without header, expected 4, found " & dtData.Rows.Count)
End Using
End Using
End Using
End Using
'//Delete our temporary file
System.IO.File.Delete(System.IO.Path.Combine(TempDir, TempFile))
End Sub
If you change the initial encoding to Unicode you'll get 8 and 9 rows in the results instead which is maybe what you're seeing. If it turns out to be an encoding problem you can add CharacterSet=Unicode to your extended properties.

Resources