Link to home
Start Free TrialLog in
Avatar of VBBRett
VBBRett

asked on

How do I replace blank spaces with a value of 0 or null?

I am writing a program to import information from an Excel spreadsheet and insert the data into a SQL Server database table.  The problem I am faced with here is that the column CAT has blank spaces in the Excel sheet.  How do I replace the blank space value with a 0 or null in VB.NET?  The first record that I tried worked fine because in the column CAT from the Excel spreadsheet, I put in a 0.  But how would I replace the blank values with a 0 or null if I was faced with a spreadsheet that gave me that type of problem using my Insert or doing something with the Insert string in my code?  Below is my code for the program.

Function ReadExcelsheet(ByVal Path As String, Optional ByVal Sheetvar As String = "Sheet1") As System.Data.DataSet

        Dim ds As New DataSet
        Dim da As New OleDbDataAdapter
        Dim conn_string As OleDbConnection
        Dim excel_cmd As New OleDbCommand
        Dim dt As New System.Data.DataTable

        Dim sql_ds As New DataSet
        Dim sql_dbadapter As New SqlDataAdapter
        Dim conn_sql As SqlConnection
        Dim sql_cmd As New SqlCommand
        Dim sql_dt As New System.Data.DataTable
        Dim cmdbuilder As New SqlCommandBuilder
        Dim tester As String





        'Make sure the text box has a string to find an Excel spreadsheet
        If TextBox1.Text = "" Or ComboBox1.Text = "" Then
            MsgBox("No spreadsheets have been loaded yet or no tables have been selected.")
            Exit Function
        Else
            'This is where the connection string is used

            Path = TextBox1.Text
            conn_string = New OleDbConnection( _
                     "Provider= Microsoft.Jet.OLEDB.4.0;" & _
                     "Data Source =" & Path & ";" & _
                     "Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";")

            'This is where the connection string reaches the SQL Server database
            conn_sql = New SqlConnection( _
    "Data Source=BRS-5C2ULHTC9ZV;Initial Catalog=NIPWork;Integrated Security=True")

            'The command connecting to a database
            excel_cmd.Connection = conn_string


            'The command string's command text
            excel_cmd.CommandText = "SELECT * FROM [" & Sheetvar & "]"

            sql_cmd.Connection = conn_sql

            'sql_cmd.CommandText = "SELECT * FROM jhirniak.NIP_Valuation"

            ' sql_cmd.CommandText = "SELECT * FROM test_nip_valuation_nonproduction"



            'da = New OleDbDataAdapter("SELECT * FROM [" & Sheet & "$]", conn_string)
            'Since the OleDbCommand stores the connection string and the command text, the line below
            'is the same as the line above.
            da.SelectCommand = excel_cmd

            'Open the connection string
            conn_string.Open()
            If conn_string.State = ConnectionState.Open Then
                MsgBox("The connection string has connected to the source.")
            Else
                MsgBox("Unable to connect")
            End If

            sql_dbadapter.SelectCommand = sql_cmd



            Try
                conn_sql.Open()
            Catch ex As Exception
                MsgBox("Unable to connect to the SQL Server database", MsgBoxStyle.Critical, "Error!")
                Exit Function
            End Try
            'Checks to see if the sql connection is open or not
            If conn_sql.State = ConnectionState.Open Then
                MsgBox("The SQL Connection is now Open")
            Else
                MsgBox("No SQL database connection was made.")
            End If



            'The data adapter fills the dataset with the table information from the database
            da.Fill(ds)
            ' da.Fill(ds, "Test_NIP_Valuation_nonproduction")
            da.Fill(dt)

            'The Sql server data adapter fills the dataset with the table information from the database
            ' sql_dbadapter.Fill(sql_ds)
            'The Sql server dataadapter fills the data table
            ' sql_dbadapter.Fill(sql_dt)





            Dim row As DataRow

            Dim retInt As Integer
            Dim count As Integer = 0
            For Each row In ds.Tables(0).Rows

                If Not row.Item("CAT").ToString = " " Then
                    row.Item("CAT").ToString.Insert(0, 0)
                End If

                tester = "insert into tblNIPIMPORT_Valuation (LineofBusiness, PolicyNO, OccuranceNO, PolOccNo, " & _
                   "PolComm, LossDay, CAT, RiskState, FirstNotice, ValnMo, AccYr, PdIndem, PdALAE, " & _
                  "OSIndem, OSALAE, IncdIndem, IncdALAE, IncdLandALAE, Insured, LossDescription) " & _
                 "values('" & row.Item("LOB").ToString & "', '" & row.Item("Pol #").ToString & "', '" & _
                row.Item("Occ #").ToString & "', '" & row.Item("Pol Occ #").ToString & "', '" & _
                 row.Item("Pol Comm").ToString & "', '" & row.Item("Loss Day").ToString & "', " & _
                row.Item("CAT").ToString & ", " & _
                row.Item("RiskState").ToString & ", '" & row.Item("First Notice").ToString & "', " & _
                row.Item("Valn Mo").ToString & ", " & row.Item("Acc Yr").ToString & ", " & _
                row.Item("PdIndem").ToString & ", " & row.Item("PdALAE").ToString & ", " & _
                row.Item("OS Indem").ToString & ", " & row.Item("OS ALAE").ToString & ", " & _
                row.Item("IncdIndem").ToString & ", " & row.Item("IncdALAE").ToString & ", " & _
                row.Item("Incd L&ALAE").ToString & ", '" & row.Item("Insured").ToString & "', '" & _
                row.Item("Loss Description") & "')"









                sql_cmd = New SqlCommand(tester, conn_sql)

                sql_cmd.ExecuteNonQuery()
                If retInt = 1 Then
                    count = count + 1
                    Continue For
                End If
                'build update
                MsgBox(tester)
                'row.SetAdded()
                count = count + 1
            Next



        End If


        ' sql_dbadapter.Update(sql_ds, tester)




        sql_dbadapter.Update(sql_ds)




        ReadExcelsheet = ds
        DataGridView1.DataSource = dt
        DataGridView2.DataSource = sql_dt
        ' UpdateSQLTable(ds)
        conn_string.Close()
    End Function
Avatar of Brian Mulder
Brian Mulder
Flag of Netherlands image

Hi VBBRett,
----------

not sure if i understand exactly what you mean but if you are faced with blanks or spaces in the CAT cell

instead of

If Not row.Item("CAT").ToString = " " Then
    row.Item("CAT").ToString.Insert(0, 0)
End If

you trim the cell and see if you're left with nothing then insert a 0

If row.Item("CAT").Trim().ToString = "" Then
    row.Item("CAT").ToString.Insert(0, 0)
End If

----------
bruintje
share what you know, learn what you don't
Avatar of VBBRett
VBBRett

ASKER

It appears that your code block and my code block of if statements don't even effect the Insert string that I have here..

tester = "insert into tblNIPIMPORT_Valuation (LineofBusiness, PolicyNO, OccuranceNO, PolOccNo, " & _
                   "PolComm, LossDay, CAT, RiskState, FirstNotice, ValnMo, AccYr, PdIndem, PdALAE, " & _
                  "OSIndem, OSALAE, IncdIndem, IncdALAE, IncdLandALAE, Insured, LossDescription) " & _
                 "values('" & row.Item("LOB").ToString & "', '" & row.Item("Pol #").ToString & "', '" & _
                row.Item("Occ #").ToString & "', '" & row.Item("Pol Occ #").ToString & "', '" & _
                 row.Item("Pol Comm").ToString & "', '" & row.Item("Loss Day").ToString & "', " & _
                row.Item("CAT").ToString & ", " & _
                row.Item("RiskState").ToString & ", '" & row.Item("First Notice").ToString & "', " & _
                row.Item("Valn Mo").ToString & ", " & row.Item("Acc Yr").ToString & ", " & _
                row.Item("PdIndem").ToString & ", " & row.Item("PdALAE").ToString & ", " & _
                row.Item("OS Indem").ToString & ", " & row.Item("OS ALAE").ToString & ", " & _
                row.Item("IncdIndem").ToString & ", " & row.Item("IncdALAE").ToString & ", " & _
                row.Item("Incd L&ALAE").ToString & ", '" & row.Item("Insured").ToString & "', '" & _
                row.Item("Loss Description") & "')"

So my question to you would be, how would I create a conditional statement to make row.Item("CAT").ToString equal to zero if there are no values from the spreadsheet for that particular cell?
i tried this

    Dim str As String = "  "
    If str.ToString().Trim() = "" Then
      str = 0
    End If

str became "0"

so you can try for the cell something like

If row.Item("CAT").Value.ToString().Trim() = "" Then
    row.Item("CAT").Value = 0
End If

if you step through it does it come by the line >row.Item("CAT").Value = 0
Avatar of VBBRett

ASKER

Hi, I'm using VB.NET 2005.  It still seems to not work.  As I step through, it does not replace the row.Item("CAT") with zero.  
Avatar of VBBRett

ASKER

By the way, I'm using Visual Studio 2005 and I'm sure that would make some kind of difference.
Avatar of VBBRett

ASKER

What is an alternative?  How would I insert 0s into the spreadsheet itself?  is there a way I can do that?
i thought you already where doing it directly into the sheet :) but pasting the code in my vb express showed that you tried to set the cell

before i try to read in an excel sheet myself can you try

                If Not row.Item("CAT").ToString.Trim = "" Then
                    row.Item("CAT").ToString.Replace(" ", "0")
                End If
Try

            If Dr.Item("CAT").ToString.Trim.Length > 1 Then
 Or    
            If String.IsNullOrEmpty(Dr.Item("CAT").ToString.Trim) Then
Avatar of VBBRett

ASKER

Still nothing.  Wow, this is annoying..lol.  Should I post my code?  Do you think that would help?
sorry had to take the not out of the if line

                If ro   w.Item("CAT").ToString.Trim = "" Then
                    row.Item("CAT").ToString.Replace(" ", "0")
                End If

i would be not surprised if a simple replace will not work ;)
Avatar of VBBRett

ASKER

Still did not work.  I don't know what is going on here with my program, but this is more difficult then it should be.
ASKER CERTIFIED SOLUTION
Avatar of Sancler
Sancler

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Let me throw my two cents worth in here, too....

System.DBNull is a tough beast to master. It doesn't cast nicely to any primitive, so you're really best to avoid it when you can.

If I recall correctly, .ToString doesn't work well on DBNull either.

Assuming you're using a T-SQL 92 compliant database engine (like SQL server), you can deal with the NULL at the database level... replace Cat in your query with ISNULL(Cat,0).
Hiya, Jeff

He's bringing in the data from Excel with an OleDb Jet Driver.

Rgoer
Or Roger, even ;-)
Oh.. I knew that. LOL.

The dreaded Nz function then:

Public Shared Function Nz(value as Object, default as Integer) As Integer
  If value Is System.DBNull.Value Then
    Return default
  Else
    Return Integer.Parse(value)
  End If
End Function

Then replace row("Cat") with Nz(row("Cat"),0)

You'll need to create different overloads of this depending on the type you want to clean up. You may also want to do some validation, such as If IsNumeric(value).