Monday, April 7, 2014

NPOI Get last used row vb.net

    Public Function GetLastRowNum(Sheet As HSSFSheet) As Integer
        Dim lastRowNum As Integer = Sheet.LastRowNum
            For rowNum As Integer = lastRowNum To 0 Step -1
                Dim row As HSSFRow = Sheet.GetRow(rowNum)
                If row Is Nothing Then Continue For

                For clmNum As Integer = 0 To row.LastCellNum
                    Dim cellVal = GetCellValue(Sheet,rowNum, clmNum)
                    If Not String.IsNullOrWhiteSpace(cellVal) Then
                        Return rowNum
                    End If
                Next
            Next
        Return lastRowNum
    End Function


 Public Function GetCellValue(ByVal sheet As HSSFSheet, ByVal rowNum As Integer, ByVal clmNum As Integer) As String
        Dim contents As String = String.Empty

        Try
            Dim row As HSSFRow = sheet.GetRow(rowNum)
            If row IsNot Nothing Then
                Dim cell As HSSFCell = row.GetCell(clmNum)
                If cell IsNot Nothing Then
                    If cell.CellType = NPOI.SS.UserModel.CellType.STRING Then
                        contents = cell.StringCellValue
                    ElseIf cell.CellType = NPOI.SS.UserModel.CellType.BLANK Then
                        contents = cell.StringCellValue
                    ElseIf cell.CellType = NPOI.SS.UserModel.CellType.NUMERIC Then
                        If HSSFDateUtil.IsCellDateFormatted(cell) Then
                            contents = cell.DateCellValue
                        Else
                            contents = cell.NumericCellValue
                        End If
                    ElseIf cell.CellType = NPOI.SS.UserModel.CellType.BOOLEAN Then
                        contents = cell.BooleanCellValue
                    ElseIf cell.CellType = NPOI.SS.UserModel.CellType.ERROR Then
                        contents = cell.ErrorCellValue
                    ElseIf cell.CellType = NPOI.SS.UserModel.CellType.Unknown Then
                        contents = cell.StringCellValue
                    ElseIf cell.CellType = NPOI.SS.UserModel.CellType.FORMULA Then
                        Select Case cell.CachedFormulaResultType
                            Case NPOI.SS.UserModel.CellType.NUMERIC
                                contents = cell.NumericCellValue
                            Case NPOI.SS.UserModel.CellType.STRING
                                contents = cell.StringCellValue
                        End Select
                    End If
                End If
            End If
        Catch ex As Exception
            ErrorLogWriter.Lines.Add(ex.Message)
        End Try

        Return contents
    End Function

No comments:

Post a Comment