Home > Software design >  How to increase or decrease the number of columns according to data in table?
How to increase or decrease the number of columns according to data in table?

Time:09-22

this is the code that prints the data in a table and each column contains multiple numbers of data. In this way, it is difficult for each column to print the exact number of data.

That's why if the number of data is three and the loop has the limit of 2 then it will not print the last data column and the loop will stop at 2.

How to adjust the columns according to data?

Required Result

╔═══╤════════════════╤═════════════════════╗
║ # │    Projects    │ Project Priorities  ║
╟━━━┼━━━━━━━━━━━━━━━━┼━━━━━━━━━━━━━━━━━━━━━╢
║ 1 │ first project  │       None          ║
║ 2 │ second project │       Low           ║
║ 3 │                │      Medium         ║
║ 4 │                │       High          ║
╚═══╧════════════════╧═════════════════════╝

Code

package main

import (
    "fmt"

    "github.com/alexeyco/simpletable"
)

func InfoTable(allData [][]string) {
    table := simpletable.New()
    table.Header = &simpletable.Header{
        Cells: []*simpletable.Cell{
            {Align: simpletable.AlignCenter, Text: "#"},
            {Align: simpletable.AlignCenter, Text: "Projects"},
            {Align: simpletable.AlignCenter, Text: "Project Priorities"},
        },
    }

    var cells [][]*simpletable.Cell

    for i := 0; i < 2; i   {
        cells = append(cells, *&[]*simpletable.Cell{
            {Align: simpletable.AlignCenter, Text: fmt.Sprintf("%d", i 1)},
            {Align: simpletable.AlignCenter, Text: allData[0][i]},
            {Align: simpletable.AlignCenter, Text: allData[1][i]},
        })
    }

    table.Body = &simpletable.Body{Cells: cells}

    table.SetStyle(simpletable.StyleUnicode)
    table.Println()
}

func main() {
    data := [][]string{
        {"first project", "second project"},
        {"None", "Low", "Medium", "High"},
    }
    InfoTable(data)
}

CodePudding user response:

There are a range of possible approaches; here is one option that removes the need to make assumptions about the number of rows/columns (playground):

func InfoTable(headings []string, allData [][]string) {
    if len(headings) != len(allData) {
        panic("Must have a heading per column")
    }
    table := simpletable.New()

    // Populate headings (adding one for the row number)
    headerCells := make([]*simpletable.Cell, len(headings) 1)
    headerCells[0] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: "#"}
    for i := range headings {
        headerCells[i 1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: headings[i]}
    }

    table.Header = &simpletable.Header{
        Cells: headerCells,
    }

    // Work out number of rows needed
    noOfCols := len(allData)
    noOfRows := 0
    for _, col := range allData {
        if len(col) > noOfRows {
            noOfRows = len(col)
        }
    }

    // Populate cells (adding row number)
    cells := make([][]*simpletable.Cell, noOfRows)
    for rowNo := range cells {
        row := make([]*simpletable.Cell, noOfCols 1) // add column for row number
        row[0] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: fmt.Sprintf("%d", rowNo 1)}

        for col := 0; col < noOfCols; col   {
            if len(allData[col]) > rowNo {
                row[col 1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: allData[col][rowNo]}
            } else {
                row[col 1] = &simpletable.Cell{Align: simpletable.AlignCenter, Text: ""} // Blank cell
            }
            cells[rowNo] = row
        }
    }
    table.Body = &simpletable.Body{Cells: cells}

    table.SetStyle(simpletable.StyleUnicode)
    table.Println()
}
  • Related