Public Function GetExcelDataforSQLInsert(ByVal fname As String) As Boolean
Dim prxls As String = fname ' excel file and path
Dim ok As Boolean = True
If Not System.IO.File.Exists(prxls) Then
MsgBox(prxls.ToString.Trim + " does not exist.")
Return False
End If
Dim xlApplication As New Application
Dim xlWrkBook As Workbook
Dim xlWorksheet As Worksheet
Dim usedRowsCount As Int32
xlApplication.Visible = False
xlApplication.DisplayAlerts = False
xlWrkBook = xlApplication.Workbooks.Open(prxls)
xlWorksheet = xlWrkBook.Worksheets(1)
usedRowsCount = xlWorksheet.UsedRange.Rows.Count ' gets count of rows
Dim i As Int32 = 0, j As Int32 = 0
Dim RowNum As Integer = 0 ' for looping thru the worksheet
Dim ColNum As Integer = 1
Dim prodcat As String = "" ' these will be the fields inserted in sqlserver table
Dim prodcde As String = ""
Dim prod As String = ""
Dim pack As String = ""
Dim cocde As String = ""
Dim upc As String = ""
Dim retList As ArrayList = Nothing ' I return errors and output params from sql with an arraylist
i = 1
Do While i <= usedRowsCount
j = getRowType(xlWorksheet, i) ' I am only importing certain rows so check these in a function
If j = 1 Then ' J tells me which cell type so I know whether to get it or not
prodcat = xlWorksheet.Cells(i, C).value.ToString.Trim ' cell I want
ElseIf j = 2 Then
RowNum += 1
prodcde = xlWorksheet.Cells(i, A).value.ToString.Trim
prod = xlWorksheet.Cells(i, C).value.ToString.Trim
pack = xlWorksheet.Cells(i, F).value.ToString.Trim
If String.IsNullOrEmpty(xlWorksheet.Cells(i, D).value) Then
cocde = ""
Else
cocde = xlWorksheet.Cells(i, D).value.ToString.Trim
End If
If String.IsNullOrEmpty(xlWorksheet.Cells(i, E).value) Then
upc = ""
Else
upc = xlWorksheet.Cells(i, E).value.ToString.Trim
End If
' just call a routine to do an insert query with the cells I have selected
retList = InsertTempXLrow(RowNum, ConnectionString, prodcat, prodcde, prod, pack, cocde, upc)
If CInt(retList.Item(0)) <> 0 Then ' return value
Dim str As String = ""
str = "ProdCat: " + prodcat + ControlChars.NewLine
str += "Prodcde: " + prodcde + ControlChars.NewLine
str += "Product: " + prod + ControlChars.NewLine
str += "ProdPack: " + pack + ControlChars.NewLine
str += ControlChars.NewLine
str += ControlChars.NewLine + "Your changes were cancelled."
MessageBox.Show(str, "Database Insert Error" + Convert.ToString(retList.Item(0)))
ok = False
Exit Do
End If
End If
i += 1
Loop
xlWrkBook.Close()
xlApplication.DisplayAlerts = True
xlApplication.Quit()
Return ok
End Function