B4J Code Snippet export Tableview to excel with jPOI

Discussion in 'B4J Code Snippets' started by iordanis lazoudis, Apr 9, 2018.

  1. iordanis lazoudis

    iordanis lazoudis Member Licensed User

    This is my first code snippet, for exporting a tableview to an excel. ITs my first serious attempt to work with b4j after trying various tools for months. I am now certain i made the best choice to start working with b4j. After searching the forum i managed to put together this sub... no big deal for some of you but for me its a huge step in programming.

    I use the jPoi library and export the data i have in TableView to excel.

    Thanks Erel for B4x.

    Code:
    Sub CreateXLfromTableView(x As TableView, sheetName As String, XLname as String)
      
        
    Dim wb As PoiWorkbook
        wb.InitializeNew(
    True'create new excel workbook
      
        
    'Create sheet and add the name we called the sub with
        Dim sheet1 As PoiSheet  
        sheet1 = wb.AddSheet(sheetName,
    0)
      
        
    'First Line has the titles from the tableview
        Dim titleRow As PoiRow = sheet1.CreateRow(0)
        
    For i = 0 To (x.ColumnsCount - 1)
            titleRow.CreateCellString(i, x.GetColumnHeader(i))
        
    Next
      
        
    'Create first data row
        Dim dataRow As PoiRow = sheet1.CreateRow(1)
      
        
    'A var to hold the values of each row
        Dim rowValues() As String

        
    'Go through each row
        For curSet = 0 To (x.Items.Size - 1)
          
            
    'Get the values of each row
            rowValues = x.Items.Get(curSet)
          
            
    'Assign the values to a temp variable to go through the values and write them to the cell
            Dim excelCell As Int = 0
            
    For Each s In rowValues  
                dataRow.CreateCellString(excelCell,s)
                excelCell = excelCell  + 
    1
            
    Next
      
            
    'Go to the next row... remember, first row is title and second row is the beginning of data...
            dataRow = sheet1.CreateRow(curSet + 2)
            dataRow.RowNumber = curSet + 
    2
        
    Next
      
        wb.Save(
    File.DirApp, XLname)
        wb.Close
      
    End Sub
     
    Last edited: Apr 9, 2018
  2. Peter Meares

    Peter Meares Member Licensed User

    Just what I needed.
    Note to other users. I had to change the
    Dim rowValues() As String
    to an Object, as I had mixed data.
    It have strange array error that only happened in release mode, not debug mode.

    Thank you.:)
     
  3. Mashiane

    Mashiane Expert Licensed User

    Will include this in my MashPoi lib, cool, thanks for this.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice