Importing data from Excel - VB.NET - asp.net

I am trying to import some data from an excel spreadsheet, using VB.net
my steps are:
first the user uploads the file to the server
then i want to read the file from the server to then populate a gridview
this is what i have:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim filepath As String = ""
If FileUpload1.HasFile Then
Try
If (FileUpload1.PostedFile.ContentType = "application/vnd.ms-excel") Then
Dim filename As String = Path.GetFileName(FileUpload1.FileName)
'Session("userid") & "-" & Date.Now()
filepath = "\excel\" & Session("userid") & "_" & Now.Date().ToString("Mdy") & "_" & filename
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
ReadExcel(filepath)
Else
StatusLabel.Text = "Only Excel file types are accepted"
End If
Catch ex As Exception
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message
End Try
End If
End Sub
Sub ReadExcel(ByVal filepath As String)
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & filepath & "';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [NSTS]", MyConnection)
MyCommand.TableMappings.Add("Table", "Net-informations.com")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
gwResults.DataSource = DtSet.Tables(0)
MyConnection.Close()
End Sub
the error happens with "MyConnection", it tried to look on the "C:/" instead of on the server:
'c:\excel\3_41911_Sample.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
how can i set the OleDb connection to get the source file from the server instead?
thank you!
nevermind, i got it
i added: Server.MapPath("~/") & filepath and now it works. however, now i'm getting the error:
The Microsoft Jet database engine could not find the object 'NSTS'. Make sure the object exists and that you spell its name and the path name correctly.
NSTS is the name of my first spreadsheet. what am i doing wrong? :(
i was missing a studip dollar sign :) ahh, it all works now!
"select * from [NSTS$]"
thanks!

Use a $ in your sheet's name in the query:
"select * from [NSTS$]"

Your c:\excel\ path is not local path but it is path local to where you are running your application.
If you are running this application from local machine, In order to map c:\excel\ path, you should either map server drive to your windows and use that drive name OR use \\excel as path value.

First - do you know exactly where on the server path the file is being saved to? I'd begin by hardcoding the path to make sure that there isn't anything else squirrely going on.
Looking at your code you're saving the file here...
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
So... first, are you sure it's saving there? If so then look as where you're reading the file with this call...
ReadExcel(filepath)
Have you tried -
ReadExcel(Server.MapPath("~/") & filepath)?

Related

Error trying to download an XML file

I'm trying to download an XML file, the file already exists in the specified path, I am not familiar with VB and probably this code is not right, I need help just in it to be able to download an existing xml file, here's the code:
Protected Sub DownloadFile(ByVal sPath As String)
Dim TargetFile As New System.IO.FileInfo(sPath)
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" +
TargetFile.Name)
Response.AddHeader("Content-Length", TargetFile.Length.ToString())
Response.ContentType = "text/xml"
Response.WriteFile(TargetFile.FullName)
Response.End()
End Sub
The error returned in the console:
Uncaught Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Contextualizing the problem:
I have serialized an object and created an XML file, then I would simply like to download this file, my difficulty is to download the file.
Dim oObj1 As New System.Xml.Serialization.XmlSerializer(GetType(eSocial.Eventos.evtTabHorTur.eSocial))
Dim sFileName = Date.Now.ToString("yyyyMMddHHmmss") & ".xml"
Dim sPath = Constantes.Ambiente.CaminhoSite & "temp\" & sFileName
Dim oFile As New System.IO.StreamWriter(sPath)
oObj1.Serialize(oFile, eSocialCamposXml)
oFile.Close()
You are saying you are having difficulty downloading but there is nothing in the code except showing writing a file and then serializing a file. You would be using a 'StreamReader' or similar manner to READ a file. Here is a simple example. Say I have an xml structure on a file location with the schema like:
<root>
<test>Data</test>
</root>
I could write this in VB.NET to get it:
Sub Main()
Dim xmlFile As XDocument
Dim fileLocation = "D:\\Test Code\\Test.xml"
Using sr = New StreamReader(fileLocation)
xmlFile = XDocument.Parse(sr.ReadToEnd())
End Using
Console.WriteLine(xmlFile.Root.Element("test").Value.ToString)
Console.ReadLine()
End Sub

Access to the path '' is denied when i try to copy a Excel in specific folder vb.net

i try to copy a file from the server on the specific folder when press a button, my code for copy the file are that:
If System.IO.File.Exists(Server.MapPath("../../TempDownloads/" & SampleOrder & ".xls")) = True Then
System.IO.File.Copy(Server.MapPath("../../TempDownloads/" & SampleOrder & ".xls"), "\\art-fs02\07_ART_ECO\12_Samples\03_Samples_order\999_MoraruVladutBOM_Test\" & SampleOrder & ".xls", True)
Else
LBL_Error.Text = "There is no file to be copied !"
GC.Collect()
Exit Sub
End If
Ok, all good, i have two application with different referinces and differents imports, but at first application work to copy my file in specific folder ("\art-fs02\07_ART_ECO\12_Samples\03_Samples_order\999_MoraruVladutBOM_Test\") but when i try to another applicatiob files doesn't work. All two application are on server.
When i put the same code in page get me error like that:
Access to the path
'\art-fs02\07_ART_ECO\12_Samples\03_Samples_order\999_MoraruVladutBOM_Test\Test.xls'
is denied.
I put a image with References for first application where my code work and references for second application and where doesn't work.
I don't know why on first application my code work, and copy the file, and the second application doesn't work.
I put all my code for page above:
Imports System.Data
Imports System.IO
Imports OfficeOpenXml
Imports System.Globalization
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Configuration
Partial Class TCO_Orders_TestCopy
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SampleOrder As String = "SO-Test"
Dim Qty As String = "55"
SampleOrder = SampleOrder.Remove(0, 3)
Dim cn As New OleDbConnection
Dim cm As New OleDbCommand
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Server.MapPath("../../FolderBOM/BOM2.xls") & ";Extended Properties=""Excel 12.0;HDR=Yes;""")
cn.Open()
With cm
.Connection = cn
.CommandText = "UPDATE [ARO list$] set info = '" & SampleOrder & "' where [SO-info] ='DVM SO no.'"
cm = New OleDbCommand(.CommandText, cn)
cm.ExecuteNonQuery()
cn.Close()
cn.Open()
.CommandText = "UPDATE [ARO list$] set info = '" & SampleOrder & "' where [SO-info] ='Local SO no.'"
cm = New OleDbCommand(.CommandText, cn)
cm.ExecuteNonQuery()
cn.Close()
cn.Open()
.CommandText = "UPDATE [ARO list$] set info = " & Qty & " where [SO-info] ='qty'"
cm = New OleDbCommand(.CommandText, cn)
cm.ExecuteNonQuery()
cn.Close()
End With
Try
My.Computer.FileSystem.CopyFile(
Server.MapPath("../../FolderBOM/BOM2.xls"),
Server.MapPath("../../TempDownloads/" & SampleOrder & ".xls"), Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Catch ex As Exception
LBL_Error.ForeColor = System.Drawing.Color.Red
LBL_Error.Text = "This SO has BOM created !"
Exit Sub
End Try
If System.IO.File.Exists(Server.MapPath("../../TempDownloads/" & SampleOrder & ".xls")) = True Then
System.IO.File.Copy(Server.MapPath("../../TempDownloads/" & SampleOrder & ".xls"), "\\art-fs02\07_ART_ECO\12_Samples\03_Samples_order\999_MoraruVladutBOM_Test\" & SampleOrder & ".xls", True)
Else
LBL_Error.Text = "There is no file to be copied !"
GC.Collect()
Exit Sub
End If
End Sub
End Class
I was going to make this a comment, but i don't have the Rep yet to comment, so i'm forced to make this an answer instead, but a lot of times when you get path access violations or file access violations a lot of times it can be the cause of invalid elevation and wont let you do any operations inside the specified path, if your trying to run it while in the editor you can always try running the editor in Admin Elevation that way it will elevate any processes made by it as well as the program your attempting to test, or you could just run it directly as Admin and see if it works properly, I've had this problem several times before and most the time it was solved by that.

Saving Files to user Computer in VB.Net

I have look for days, with no luck.
Can anyone tell me how to save files in VB.Net to any computer? There are lost of articles, but those only tell you about saving to your own computer by giving folder access, not a random user's computer.
You can see my example here http://hanontest.com/POShellCreator.aspx (You have to enter text into task code, project id and notes field, then click create. Then click export, you will see the error.)
I can go to a local Pizza shop website and download a menu pdf, I know its possible.
In my example it saves when you click the button, I would like a save as dialog if anyone knows how to do that as well.
Here is the save string:
Dim regDate As Date = Date.Now()
Dim strDate As String = regDate.ToString(".yyyy\.MM\.dd")
TextBox5.Text = "c:\temp\" & Vendor & "&" & Vendor2 & "&" & Vendor3 & "&" & Vendor4 & TaskEmpty & strDate & ".csv"
Here is how I am saving:
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Define Path to save file.
Dim path As String = TextBox5.Text
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(TextBox3.Text)
fs.Write(info, 0, info.Length)
fs.Close()
End Sub
The error you're seeing there is because you're attempting to save the text file to the server's
file system, which you don't have write access to.
To return a file to user from the server you need to do a little more work, and it's not going to simple on a postback from a button.
You need to send the data down to the client in the Response.OutputStream, instead of your page, and also tell the browser to treat it as a file download:
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=textFile.csv");

Overload File Function VB.NET

I am trying to create an onclick function through ASP front end to check if a file exists, if not create it and write textbox text to it, currently getting an error on the below code saying that I cannot overload the file function, is there a better way of doing this?
UPDATE
The issue is the file is still open when trying to write to it which is throwing the error.
Please see below code:
Protected Sub Create_Click(sender As Object, e As EventArgs)
Dim txtFile As String = "E:Documents\Visual Studio 2013\Projects\SomeProject\Templates\" & FileName.Text & ".txt"
If File.Exists(txtFile) Then
Response.Write("A file of that name already exists.")
Else
File.Create(txtFile)
File.WriteAllText(eTemplate.Text)
End If
End Sub
I have also tried:
If File.Exists(txtFile) Then
Response.Write("A file of that name already exists.")
Else
System.IO.File.Create(txtFile)
Dim sw As New StreamWriter(txtFile, True)
sw.Write(eTemplate.Text)
sw.Close()
End If
You're right on the money, it is because it needs to be closed first.
I created a file stream instance first, created the file, closed it and then wrote to it. Put the below code in yours or write it out, but remember to correct the file path.
Protected Sub Create_Click(sender As Object, e As EventArgs)
Dim txtFile As String = "E:\wherever\" & FileName.Text & ".txt"
If System.IO.File.Exists(txtFile) Then
Dim message As String = "A file by this name already exists, choose another or update the existing file."
Else
Dim fs As FileStream = File.Create(txtFile)
fs.Close()
Dim sw As New StreamWriter(txtFile, True)
sw.Write(eTemplate.Text)
sw.Close()
End If
End Sub

Reading, parsing and posting data from a .csv file into a SQL database asp.net

I have the following data that basically I only need a few bits of information from:
Resource:X - Y;Z - Å;Type:(all) From Date:
07/12/2010 - To Date 07/12/2010 Sort
by:Time Include Referring
source/physician:No Footer:Default
Criteria:None
","Appointments","X,
Y","ZAssociates","Monday, July 12,
2010","Time","Patient Name","Patient
ID","Appt. Type","Ref. Source/
Physician","Phone","Type","DOB
","Z, X","Y","7/12/2010
12:00:00AM","Time","Patient
Name","Patient ID","Appt.
Type","Phone","Type","DOB "," 7:30
[snip]
The only things I need from this are:
Patients Name
Drs Name
Patients Phone Number
Appt Time
Appt Date
and the rest of the information I can discard. A customer uploads this as a .csv file (even though it really isn't as you can see) and I'd like to parse the needed information and post that to my SQL database and discard the rest. I think I can do this with a dataset but I've never built that before. The fields from the customer will always be the same and the fields I will need will always be the same.
Also, the date time has to be in the format of yyyy/mm/dd:hhmm and the phone number always has to have 512 as a prefix. Here is the code I currently have for my site:
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim SaveLocation = "\\xxxWEB3\wwwroot\Webfile1\Reminders\Doug_Ancil\doug.csv"
If UploadFile(SaveLocation) Then
'the file was uploaded: now try saving it to the database
SaveToDatabase(SaveLocation)
End If
End Sub
Private Function UploadFile(ByVal SavePath As String) As Boolean
Dim fileWasUploaded As Boolean = False 'indicates whether or not the file was uploaded
'Checking if the file upload control contains a file
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
Try
'checking if it was .txt file BEFORE UPLOADING IT!
'You used to upload it first...but the file could be a virus
If File1.FileName = ("doug.csv") = False Then
'The file is not the expected type...do not upload it
'just post the validation message
message.Text = "Sorry, thats not the correct file."
message2.Text = "Please locate and upload 'doug.csv'"
Else
'The file is a .txt file
'checking to see if the file exists already
'If it does exist Deleting the existing one so that the new one can be created
If IO.File.Exists(SavePath) Then
IO.File.Delete(SavePath)
End If
'Now upload the file (save it to your server)
File1.PostedFile.SaveAs(SavePath)
'After saving it check to see if it exists
If File.Exists(SavePath) Then
'Upload was sucessful
message.Text = "Thank you for your submission."
fileWasUploaded = True
Else
'the file was not saved
message.Text = "Unable to save the file."
End If
End If
Catch Exc As Exception
'We encountered a problem
message.Text = "Your file was not in the correct format. Please contact Customer Service at xxxx-xxxx-xxxx."
End Try
Else
'No file was selected for uploading
message.Text = "Please select a file to upload."
End If
Return fileWasUploaded
End Function
Private Sub SaveToDatabase(ByVal SavePath As String)
Try
Dim sqlQueryText As String = _
"BULK INSERT dialerresults " + _
"FROM '" & SavePath & "' " + _
"WITH ( FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n' )"
' and bulk import the data:
'If ConfigurationManager.ConnectionStrings("Dialerresults") IsNot Nothing Then
'Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
Dim connection As String = "data source=10.2.1.40;initial catalog=IVRDialer;uid=xxxx;password=xxxxx;"
Using con As New SqlConnection(connection)
con.Open()
' execute the bulk import
Using cmd As New SqlCommand(sqlQueryText, con)
cmd.ExecuteNonQuery()
End Using
End Using
'Else
'message.Text="ConfigurationManager.ConnectionStrings('Dialerresults') is Nothing!"
'End If
Catch ex As Exception
message.Text = "Your file was not in the correct format. Please contact Customer Service at xxxxxxx."
End Try
End Sub
End Class
Thank you,
Doug
Personally, I'd use a library like FileHelpers to parse/load the data then whatever my typical means of data access for this app is to update it.

Resources