locked
Upload Excel in to SQL databse -VB.NET RRS feed

  • Question

  • User-1578974752 posted

    I have an excel sheet with 5 columns which are 5 fields in the database registration table. when i upoad that excel using File upload, how can i insert in to the registration table all the user details in the excel sheet .Appreciate your help

    Monday, August 20, 2018 11:44 AM

Answers

All replies

  • User1120430333 posted

    You would make a custom type like a DTO, you populate the DTO from data on the excel file and you use the DTO with parmterized inline T-SQL or parmterized Stored Procedure and populate the SQL parameters from the DTO.

    https://www.codeguru.com/vb/gen/vb_misc/oop/article.php/c7063/Data-Transfer-Object-Pattern-Goes-VBNET.htm

    https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/auto-implemented-properties

    https://www.aspsnippets.com/Articles/Parameterized-Queries-ADO.Net.aspx

    Dim strQuery As String
    Dim cmd As SqlCommand
    strQuery = "insert into customers (CustomerID, CompanyName) values(@CustomerID, @CompanyName)"
    cmd = New SqlCommand(strQuery)
    cmd.Parameters.AddWithValue("@CustomerID", DTO.CustomerID)
    cmd.Parameters.AddWithValue("@CompanyName", DTO.NAMR)
    InsertUpdateData(cmd)
    
    ======================================================
    
    Public Class DtoProject
    
        Public Property ProjectId As Int32
        Public Property ClientName As String
        Public Property ProjectName As String
        Public Property Technology As String
        Public Property ProjectType As String
        Public Property UserId As String
        Public Property StartDate  As DateTime
        Public Property EndDate As DateTime? 
        Public Property Cost As Decimal
       
    End Class

    Monday, August 20, 2018 12:49 PM
  • User283571144 posted

    Hi shsu,

    I have an excel sheet with 5 columns which are 5 fields in the database registration table. when i upoad that excel using File upload, how can i insert in to the registration table all the user details in the excel sheet .Appreciate your help

    According to your description, I suggest you could firstly store the excel into your server, then you could read the data from the excel using OleDb library and insert it into database. 

    More details, you could refer to below codes:

    My test table:

    CREATE TABLE [dbo].[Employee](  
        [id] [int] IDENTITY(1,1) NOT NULL,  
        [Name] [varchar](50) NULL,  
        [City] [varchar](50) NULL,  
       
     CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
    (  
        [id] ASC  
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
    ) ON [PRIMARY]  

    Excel:

    Aspx:

    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ExcelTest.aspx.vb" Inherits="VBidentityTrue.ExcelTest" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                                    <asp:FileUpload ID="FileUpload1" runat="server" />  
    
                                    <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click"/>  
    
    
            </div>
        </form>
    </body>
    </html>
    

    Code-behind:

    Notice: Since I use Microsoft.Jet.OLEDB.4.0, it could only read the xls excel. If you want to use xlxs, you should use oledb.12.0.

    Imports System.Data.OleDb
    Imports System.Data.SqlClient
    Imports System.IO
    
    Public Class ExcelTest
        Inherits System.Web.UI.Page
    
        Private Econ As OleDbConnection
        Private con As SqlConnection
        Private constr, Query, sqlconn As String
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
        End Sub
        Private Sub ExcelConn(ByVal FilePath As String)
            constr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                       "Data Source=" + FilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;';"
            Econ = New OleDbConnection(constr)
        End Sub
    
        Protected Sub Button1_Click(sender As Object, e As EventArgs)
            FileUpload1.SaveAs(Server.MapPath("excel") + FileUpload1.PostedFile.FileName)
            InsertExcelRecords(Server.MapPath("excel") + FileUpload1.PostedFile.FileName)
        End Sub
    
        Private Sub InsertExcelRecords(ByVal FilePath As String)
            ExcelConn(FilePath)
            Query = String.Format("select * from [{0}$]", "Sheet1")
            Dim Ecom As OleDbCommand = New OleDbCommand(Query, Econ)
            Econ.Open()
            Dim ds As DataSet = New DataSet()
            Dim oda As OleDbDataAdapter = New OleDbDataAdapter(Query, Econ)
            Econ.Close()
            oda.Fill(ds)
            Dim Exceldt As DataTable = ds.Tables(0)
            connection()
            Dim objbulk As SqlBulkCopy = New SqlBulkCopy(con)
            objbulk.DestinationTableName = "Employee"
            objbulk.ColumnMappings.Add("Name", "Name")
            objbulk.ColumnMappings.Add("City", "City")
            con.Open()
            objbulk.WriteToServer(Exceldt)
            con.Close()
        End Sub
    
        Private Sub connection()
            sqlconn = "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=aspnet-VBidentityTrue-201805070401328;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
            con = New SqlConnection(sqlconn)
        End Sub
    
    
    End Class

    Result:

    Best Regards,

    Brando

    Tuesday, August 21, 2018 8:17 AM
  • User-1578974752 posted

    Thanks Brando

    I am using vs 2017 . The given path's format is not supported. error message is showing. for(FileUpload1.SaveAs(Server.MapPath("excel") + FileUpload1.PostedFile.FileName) )

    when I take out that

    System.Data.OleDb.OleDbException  Cannot update.  Database or object is read-only.  for Econ.Open()

    Tuesday, August 21, 2018 9:34 AM
  • User283571144 posted

    Hi shsu,

    I am using vs 2017 . The given path's format is not supported. error message is showing. for(FileUpload1.SaveAs(Server.MapPath("excel") + FileUpload1.PostedFile.FileName) )

    Could you please tell me how you solved the path not found error?

    According to the OleDbException , it means the excel is read-only or you don't have the permission to access it.

    I suggest you could firstly open the excel's path and make sure you could update and delete it.

    Like below:

    Best Regards,

    Brando

    Wednesday, August 22, 2018 3:08 AM
  • User1120430333 posted

    You could have used Linq-2-Excel too and just pointed to the excel file.

    http://www.dotnetfunda.com/codes/show/7580/how-to-read-an-excel-file-using-linqtoexcel-project-in-vbnet

    You could do a Linq projection using anaymous type or concrete type like a DTO and used either one as a parameter in a parameterized inline T-SQL statment.

     http://www.howtoasp.net/database-tutorials/linq-tutorials/how-to-use-linq-expression-to-do-projection-in-vb-net/

    https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/anonymous-types

    https://www.nuget.org/packages/LinqToExcel/

    Wednesday, August 22, 2018 5:14 AM
  • User-1578974752 posted

    Thanks Brando

    I updated the properties as you said.  But still below message is showing. C:\inetpub\wwwroot\Test\Test\Uploadss  Here I saved the excel

    and tried with this code also ->   FileUpload1.SaveAs(Server.MapPath("Uploadss\") + FileUpload1.PostedFile.FileName) still error

    For -> FileUpload1.SaveAs(Server.MapPath("excel") + FileUpload1.PostedFile.FileName)

    error showing is as below

    The given path's format is not supported. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NotSupportedException: The given path's format is not supported.

    Stack trace

    [NotSupportedException: The given path's format is not supported.]
       System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath) +12767947
       System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) +490
       System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) +60
       System.IO.FileStream..ctor(String path, FileMode mode) +55
       System.Web.HttpPostedFile.SaveAs(String filename) +94
       System.Web.UI.WebControls.FileUpload.SaveAs(String filename) +24
       Test.WebForm11.Button1_Click(Object sender, EventArgs e) in C:\inetpub\wwwroot\Test\Test\WebForm11.aspx.vb:23
       System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9815774
       System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
       System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
       System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
       System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

    Thursday, August 23, 2018 9:22 AM
  • User283571144 posted

    Hi shsu,

    I suggest you could set a breakpoint to see what the path generated by the "Server.MapPath("Uploadss\") + FileUpload1.PostedFile.FileName".

    Besides, I suggest you could consider using path.combine method.

            Dim path As String = Server.MapPath("Uploadss\")
            System.IO.Path.Combine(path, fileName)

    Best Regards,

    Brando

    Tuesday, September 4, 2018 9:58 AM
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 4, 2018 12:00 PM
  • User-1709371596 posted

    i have a problem dude. its 2018 now and I have problem using the latest import wizard. I tried importing xls and csv file but the column names (written in UTF-8 English) were messed and I couldn't get it right. Do you mind writing a newer answer?

    Thanks a lot.

    Nubemedia

    Tuesday, September 4, 2018 12:15 PM
  • User-1578974752 posted

    Hi Mudassarkhan

    Thanks for the help.

    The above code is working fine.

    My table is having a unique id as emailid .Is it possible to check whether same emailid is there in the table, and if so delete the old values in the database after File upload.

    For example 1000 employees are already in the database.Now I am uploading 1000 employees datas through file upload ,in which 400 are with same name and eamil id(same as in the database).After uploading i want to delete 400 old records which have same emailid from the database table

    Wednesday, September 5, 2018 5:57 AM
  • User-1171043462 posted

    With SQLBulkCopy you cannot but I have another Solution as well

    SqlBulkCopy- Bulk Insert records and Update existing rows if record exists using C# and VB.Net

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 5, 2018 10:58 AM
  • User-1578974752 posted

    Hi Mudassarkhan

    Thanks for the great article.

    Actually I have to Delete the old records with same UserName (which is actually email) where created date < sysdate.

    After your Bulk upload code ,I have paced below code inside Protected Sub Upload(sender As Object, e As EventArgs).

    But my issue is some times it is deleting the old records with created date before system date and with same username, but some times all the records are deleting .Can please inform how to update this.

    ID.Text = Date.Now

    cmd.CommandText = "delete from tblPersons where exists (Select personId from tblPersons t2 where t2.UserName = tblPersons.UserName and CreatedDate < '" + ID.Text + "')"

    to suit my request.

      cmd.CommandText = "delete from tblPersons where exists (Select personId from tblPersons t2 where t2.UserName = tblPersons.UserName and CreatedDate < '" + ID.Text + "')"

     cmd.ExecuteNonQuery()

    cmd.Dispose()

    Catch ex As Exception

    Finally

    cmd.Dispose()

     

    End Try

     

     

     

    Thursday, September 6, 2018 2:57 AM
  • User-1578974752 posted

    Uploading is working fine in the test server. But when I open through the link from  local host . Below error is showing when I click the Upload. Appreciate the help

    The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

    Wednesday, September 12, 2018 8:14 AM