1 回答

TA貢獻1821條經驗 獲得超6個贊
有一系列可能的方法;這是一個選項,無需對行數/列數做出假設(操場):
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()
}
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報