美文网首页
Golang对excel进行处理

Golang对excel进行处理

作者: 也许会了 | 来源:发表于2021-04-30 16:38 被阅读0次

    之前有关Golang的文章主要是基于Golang的标准库来讲解的,今天我们来看看Golang的一个开源库,它可以用来处理xlsx文件,首先下载包

    go get github.com/tealeg/xlsx

    我们通过一个简单的例子看看这个包如何使用,这个例子主要实现输入列名,将表格中该列的所有数据进行显示。代码如下所示:

    package main

    import (

    "bufio"

    "fmt"

    "os"

    "github.com/tealeg/xlsx"

    )

    func main() {

    if len(os.Args) != 3 {

    fmt.Println("Usage: xlsx pathname sheetname")

    os.Exit(1)

    }

    xlsxFile, err := xlsx.OpenFile(os.Args[1])

    if err != nil {

    fmt.Println(err)

    os.Exit(1)

    }

    sheet := xlsxFile.Sheet[os.Args[2]]

    if sheet == nil {

    fmt.Println("表单名不存在")

    os.Exit(1)

    }

    for {

    title := getStdinInput("请输入列名:")

    if title == "" {

    fmt.Println(title)

    continue

    }

    titleColIndex := findColByTitle(sheet, title)

    if titleColIndex == -1 {

    fmt.Println("列名不存在")

    continue

    }

    rowLen := len(sheet.Rows)

    result := []string{}

    for rowIndex := 1; rowIndex < rowLen; rowIndex++ {

    content := sheet.Cell(rowIndex, titleColIndex).String()

    result = append(result, content)

    }

    fmt.Println(result)

    }

    }

    func getStdinInput(hint string) string {

    fmt.Print(hint)

    scanner := bufio.NewScanner(os.Stdin)

    if scanner.Scan() {

    return scanner.Text()

    }

    return ""

    }

    func findColByTitle(sheet *xlsx.Sheet, title string) int {

    titleRow := sheet.Rows[0]

    for titleIndex, col := range titleRow.Cells {

    if col.String() == title {

    return titleIndex

    }

    }

    return -1

    }

    先看主函数,主函数首先进行命令行参数校验,使用该程序需要使用两个参数,一个是xlsx的路径,一个是需要使用的表单名称。之后打开xlsx文件和对应的表单,通过标准输入读取列名,然后在对应的表单中查找列名,通过遍历所有行,获取该列的所有数据。从标准输入读取数据和查找对应的列索引这里封装了两个函数。

    getStdinInput()函数接收一个参数,作为输入的提示语句,该函数基于scanner获取标准输入的文本。

    findColByTitle()函数传入两个参数:表单对象的指针和列名。通过遍历所有的标题行中的列,查找匹配的列索引并返回。

    可以自己创建一个标准的xlsx文件,第一行是标题行,然后实用程序测试一下,之前有使用Python做Excel处理,但是感觉运行效率还是Golang更好一些。

    本文来自php中文网的golang栏目:https://www.php.cn/be/go/

    相关文章

      网友评论

          本文标题:Golang对excel进行处理

          本文链接:https://www.haomeiwen.com/subject/cvonrltx.html