Maison  >  Article  >  développement back-end  >  Comment ajouter des commentaires de tableau dans Golang

Comment ajouter des commentaires de tableau dans Golang

PHPz
PHPzoriginal
2023-04-04 17:28:11721parcourir

Ces dernières années, le développement de programmes Golang est devenu de plus en plus populaire en raison de ses caractéristiques telles que l'efficacité, la simplicité, la stabilité et la sécurité. Comme les tableaux sont largement utilisés dans diverses applications à grande échelle, les programmes Golang doivent également traiter des données tabulaires. Dans les programmes Golang, nous devons souvent ajouter des commentaires aux tableaux pour faciliter la compréhension des données. Cet article explique comment ajouter des commentaires de tableau dans Golang.

1. Qu'est-ce qu'un commentaire de tableau ?

Un commentaire de tableau est un court paragraphe de texte ou d'expression mathématique ajouté à une cellule de tableau pour clarifier les informations de la cellule de manière spécifique et précise. Les commentaires du tableau sont généralement utilisés pour les données clés ou les explications des données dans le tableau afin d'aider les utilisateurs à mieux comprendre les données.

2. Pourquoi les annotations de tableau sont nécessaires

Dans les tableaux riches en données, les utilisateurs peuvent avoir besoin de plus d'informations pour comprendre les données. À ce stade, les commentaires du tableau jouent un rôle important. De plus, des annotations sont également nécessaires dans les outils de visualisation de données tabulaires pour aider les utilisateurs à mieux comprendre les données.

3. Comment ajouter des commentaires de tableau

La méthode d'ajout de commentaires de tableau dans le programme Golang est la suivante :

  1. Utilisez la bibliothèque Excel

Vous pouvez utiliser la bibliothèque Excel pour lire et écrire des fichiers au format Excel. La bibliothèque Excel fournit des méthodes pour utiliser les cellules Excel et prend en charge l'ajout de commentaires aux cellules. Voici un exemple simple :

package main

import (
    "fmt"
    "github.com/tealeg/xlsx"
)

func main() {
    file := xlsx.NewFile()
    sheet, err := file.AddSheet("Sheet1")
    if err != nil {
        fmt.Println(err)
    }

    row := sheet.AddRow()
    cell := row.AddCell()
    cell.Value = "data"
    comment := `This is a comment`
    cell.SetComment(comment, "Golang")
    err = file.Save("test.xlsx")
    if err != nil {
        fmt.Println(err)
    }
}
  1. Utilisation de la bibliothèque Tablewriter

La bibliothèque Tablewriter est une bibliothèque permettant de créer une interface de ligne de commande qui peut générer des données sous forme de tableau et prend en charge l'ajout de commentaires aux cellules d'un tableau. Voici un exemple simple :

package main

import (
    "fmt"
    "os"
    "github.com/olekukonko/tablewriter"
)

func main() {
    data := [][]string{
        {"A", "B", "C"},
        {"1", "2", "3"},
    }

    table := tablewriter.NewWriter(os.Stdout)
    table.SetHeader([]string{"col1", "col2", "col3"})

    for _, v := range data {
        table.Append(v)
    }
    table.SetCaption(true, "This is a caption")
    table.SetFooter([]string{"", "", "total"})
    table.SetBorder(false)
    table.SetAlignment(tablewriter.ALIGN_LEFT)

    table.Render()

    fmt.Println("\n")

    table.SetFooter([]string{"", "total", "6"})
    table.SetFooterAlignment(tablewriter.ALIGN_RIGHT)
    table.Render()

    fmt.Println("\n")

    table.SetFooter([]string{"", "total=6", ""})
    table.SetFooterAlignment(tablewriter.ALIGN_CENTER)
    table.Render()

    fmt.Println("\n")

    table.SetFooter([]string{"", "", "6"})
    table.SetFooterColor(tablewriter.Colors{tablewriter.FgGreenColor}, tablewriter.Colors{}, tablewriter.Colors{})
    table.SetFooterAlignment(tablewriter.ALIGN_LEFT)
    table.SetFooterLine(false)
    table.Render()

    fmt.Println("\n")

    table.SetFooter([]string{"", "", "6"})
    table.SetFooterColor(tablewriter.Colors{tablewriter.FgRedColor}, tablewriter.Colors{}, tablewriter.Colors{})
    table.SetFooterAlignment(tablewriter.ALIGN_RIGHT)
    table.SetFooterLine(true)
    table.Render()

    fmt.Println("\n")

    table.SetBorder(true)
    table.SetCaption(true, "This is a caption")
    table.SetAutoMergeCells(true)
    table.Append([]string{"1", "2", "3"})
    table.Append([]string{"4", "5", "6"})
    table.SetCell(0, 0, tablewriter.Color(tablewriter.FgYellowColor), tablewriter.BgGreenColor, "test")
    table.SetCell(0, 1, tablewriter.Colors{tablewriter.Bold}, tablewriter.BgBlackColor, "bold")
    table.SetCell(0, 2, tablewriter.Colors{}, tablewriter.BgBlackColor, "normal")
    table.SetCell(1, 0, "", "", "not colored")
    table.SetCell(1, 1, "", "", "not colored")
    table.SetCell(1, 2, "", "", "not colored")
    table.SetCell(2, 0, tablewriter.Colors{tablewriter.FgRedColor, tablewriter.Bold}, tablewriter.BgWhiteColor, "red bold")
    table.SetCell(2, 1, tablewriter.Colors{tablewriter.FgHiRedColor, tablewriter.Bold}, tablewriter.BgWhiteColor, "hi red bold")
    table.SetCell(2, 2, tablewriter.Colors{tablewriter.FgHiRedColor}, tablewriter.BgWhiteColor, "hi red")
    table.SetCell(2, 2, tablewriter.Colors{tablewriter.FgHiRedColor}, tablewriter.BgWhiteColor, "hi red")
    table.SetCaption(true, "This is a caption")
    table.SetCaptionAlign(tablewriter.ALIGN_CENTER)
    table.Append([]string{"7", "8", "9"})
    table.Render()

    fmt.Println("\n")

    table.ClearRows()
    table.SetHeader([]string{"Name", "Age", "Money"})
    table.SetAutoWrapText(false)
    table.SetHeaderColor(tablewriter.Colors{tablewriter.FgHiBlueColor}, tablewriter.Colors{tablewriter.BgBlackColor}, tablewriter.Colors{})
    table.SetColumnColor(tablewriter.Colors{tablewriter.Bold}, tablewriter.Colors{tablewriter.BgYellowColor}, tablewriter.Colors{})
    table.SetColumnAlignment([]int{tablewriter.ALIGN_LEFT, tablewriter.ALIGN_LEFT, tablewriter.ALIGN_LEFT})
    table.SetTablePadding("\t")
    table.SetBorder(false)

    for i := 1; i <= 10; i++ {
        data := []string{fmt.Sprintf("user%d", i), fmt.Sprintf("%d", i*10), fmt.Sprintf("$%d.00", i*100)}
        table.Append(data)
    }

    table.SetRowLine(true)
    table.SetRowSeparator("-")
    table.Render()

    fmt.Println("\n")

    table.ClearRows()
    table.SetHeader([]string{"City", "Population"})
    table.SetHeaderAlignment(tablewriter.ALIGN_CENTER)
    table.SetHeaderColor(tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiRedColor}, tablewriter.Colors{tablewriter.Bold}, tablewriter.Colors{})
    table.SetRowColor(tablewriter.Color(tablewriter.FgWhiteColor), tablewriter.Color(tablewriter.FgWhiteColor))
    table.SetColumnSeparator("|")
    table.SetRowSeparator("-")
    table.SetBorder(true)

    for _, v := range [][]string{
        {"Shanghai", "25000000"},
        {"Beijing", "21800000"},
    } {
        table.Append(v)
    }

    table.Render()

    fmt.Println("\n")

    table.ClearRows()
    table.SetOutputMirror(os.Stdout)
    table.SetAutoWrapText(false)
    table.SetHeader([]string{"Name", "NickName"})
    table.SetFooter([]string{"", "total"})
    table.SetFooterAlignment(tablewriter.ALIGN_CENTER)
    table.SetFooterColor(tablewriter.Colors{tablewriter.Bold}, tablewriter.Colors{})
    table.SetCaption(true, "This is a caption")
    table.SetCaptionAlignment(tablewriter.ALIGN_LEFT)

    table.AppendBulk([][]string{[]string{"JJJ", "kkk"}, []string{"kkk", "lll"}, []string{"aaa", "bbb"}})
    table.Render()

    fmt.Println("\n")

    table.ClearRows()
    table.SetHeader([]string{"Name", "NickName"})
    table.SetFooter([]string{"", "total"})

    for i := 1; i <= 100; i++ {
        table.Append([]string{fmt.Sprintf("user%d", i), fmt.Sprintf("nick%d", i)})
    }

    table.SetAutoWrapText(true)
    table.SetRowLine(true)
    table.SetHeaderLine(false)
    table.SetFooterLine(false)
    table.SetCaption(true, "This is a caption")
    table.AppendFooter([]string{"", "total=100"})
    table.Render()

    fmt.Println("\n")
}

Les annotations de tableau peuvent être implémentées dans n'importe quelle cellule de la bibliothèque Tablewriter dans cet exemple. Vous pouvez utiliser la méthode SetFooter pour ajouter une annotation globale, ou vous pouvez utiliser des méthodes telles que SetFontColor pour embellir davantage le tableau. .

4. Résumé

Cet article explique comment ajouter des commentaires de table dans les programmes Golang. Les annotations de tableau peuvent aider les utilisateurs à mieux comprendre les données tabulaires et également les rendre plus attrayantes. Il existe de nombreuses façons d'ajouter des commentaires de tableau dans les programmes Golang, parmi lesquelles l'utilisation de la bibliothèque Excel et de la bibliothèque Tablewriter est la plus simple. La prochaine fois que vous travaillerez avec des données tabulaires, essayez ces méthodes pour rendre les données plus faciles à comprendre et à gérer.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn