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;Ini tial 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_nonprod uction"
'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.SelectComman d = 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_nonpro duction")
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.I nsert(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").ToSt ring & ", '" & row.Item("First Notice").ToString & "', " & _
row.Item("Valn Mo").ToString & ", " & row.Item("Acc Yr").ToString & ", " & _
row.Item("PdIndem").ToStri ng & ", " & row.Item("PdALAE").ToStrin g & ", " & _
row.Item("OS Indem").ToString & ", " & row.Item("OS ALAE").ToString & ", " & _
row.Item("IncdIndem").ToSt ring & ", " & row.Item("IncdALAE").ToStr ing & ", " & _
row.Item("Incd L&ALAE").ToString & ", '" & row.Item("Insured").ToStri ng & "', '" & _
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_d s, tester)
sql_dbadapter.Update(sql_d s)
ReadExcelsheet = ds
DataGridView1.DataSource = dt
DataGridView2.DataSource = sql_dt
' UpdateSQLTable(ds)
conn_string.Close()
End Function
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;Ini
'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_nonprod
'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.SelectComman
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_nonpro
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.I
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").ToSt
row.Item("Valn Mo").ToString & ", " & row.Item("Acc Yr").ToString & ", " & _
row.Item("PdIndem").ToStri
row.Item("OS Indem").ToString & ", " & row.Item("OS ALAE").ToString & ", " & _
row.Item("IncdIndem").ToSt
row.Item("Incd L&ALAE").ToString & ", '" & row.Item("Insured").ToStri
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_d
sql_dbadapter.Update(sql_d
ReadExcelsheet = ds
DataGridView1.DataSource = dt
DataGridView2.DataSource = sql_dt
' UpdateSQLTable(ds)
conn_string.Close()
End Function
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").ToSt ring & ", '" & row.Item("First Notice").ToString & "', " & _
row.Item("Valn Mo").ToString & ", " & row.Item("Acc Yr").ToString & ", " & _
row.Item("PdIndem").ToStri ng & ", " & row.Item("PdALAE").ToStrin g & ", " & _
row.Item("OS Indem").ToString & ", " & row.Item("OS ALAE").ToString & ", " & _
row.Item("IncdIndem").ToSt ring & ", " & row.Item("IncdALAE").ToStr ing & ", " & _
row.Item("Incd L&ALAE").ToString & ", '" & row.Item("Insured").ToStri ng & "', '" & _
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?
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").ToSt
row.Item("Valn Mo").ToString & ", " & row.Item("Acc Yr").ToString & ", " & _
row.Item("PdIndem").ToStri
row.Item("OS Indem").ToString & ", " & row.Item("OS ALAE").ToString & ", " & _
row.Item("IncdIndem").ToSt
row.Item("Incd L&ALAE").ToString & ", '" & row.Item("Insured").ToStri
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.ToSt ring().Tri m() = "" Then
row.Item("CAT").Value = 0
End If
if you step through it does it come by the line >row.Item("CAT").Value = 0
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.ToSt
row.Item("CAT").Value = 0
End If
if you step through it does it come by the line >row.Item("CAT").Value = 0
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.
ASKER
By the way, I'm using Visual Studio 2005 and I'm sure that would make some kind of difference.
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.T rim = "" Then
row.Item("CAT").ToString.R eplace(" ", "0")
End If
before i try to read in an excel sheet myself can you try
If Not row.Item("CAT").ToString.T
row.Item("CAT").ToString.R
End If
Try
If Dr.Item("CAT").ToString.Tr im.Length > 1 Then
Or
If String.IsNullOrEmpty(Dr.It em("CAT"). ToString.T rim) Then
If Dr.Item("CAT").ToString.Tr
Or
If String.IsNullOrEmpty(Dr.It
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.Tri m = "" Then
row.Item("CAT").ToString.R eplace(" ", "0")
End If
i would be not surprised if a simple replace will not work ;)
If ro w.Item("CAT").ToString.Tri
row.Item("CAT").ToString.R
End If
i would be not surprised if a simple replace will not work ;)
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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).
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
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).
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).
----------
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.I
End If
you trim the cell and see if you're left with nothing then insert a 0
If row.Item("CAT").Trim().ToS
row.Item("CAT").ToString.I
End If
----------
bruintje
share what you know, learn what you don't