Tuesday, October 1, 2013

Open xlsx and read data or edit data

Public Sub ReadXlsx(FilePath As String)
        Dim wb As XSSFWorkbook = Nothing
        Try
            'Open book here
            Using fs As New FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Read)
                wb = New XSSFWorkbook(fs)
            End Using
 
            'Get sheet by the name
            Dim sht1 As XSSFSheet = wb.GetSheet("Sheet1")
 
            'Get sheet by the index
            Dim sht2 As XSSFSheet = wb.GetSheetAt(1)
 
            'Get userd last row
            Dim lastRow As Integer = sht1.LastRowNum
 
            'Get lastColumn(every singal row has last column)
            Dim lastClm As Integer = sht1.GetRow(0).LastCellNum
 
            'Get cell 'A1'
            Dim cell1 As XSSFCell = sht1.GetRow(0).GetCell(0)
 
            'Get CellStyle
            Dim cell1Style As XSSFCellStyle = cell1.CellStyle
 
            'Get cell value(Cell has type; better to check type and then get cell value)
            Dim cellvalue As String = cell1.StringCellValue
 
            'Set cell value(Before set cell value needs to check cell is exist)
            cell1.SetCellValue("MY TEXT")
 
            'Create row
            Dim row1 As XSSFRow = sht1.GetRow(0)
            If row1 Is Nothing Then sht1.CreateRow(0)
 
            'Create cell
            Dim cell2 As XSSFCell = row1.GetCell(1)
            If cell2 Is Nothing Then row1.CreateCell(1)
 
 
        Catch ex As Exception
            Console.Write(ex.Message)
        End Try
 End Sub

No comments:

Post a Comment