详解Golang如何对excel进行处理


当前第2页 返回上一页

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

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文件,第一行是标题行,然后实用程序测试一下,之前有使用PythonExcel处理,但是感觉运行效率还是Golang更好一些。

以上就是详解Golang如何对excel进行处理的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

golang 开发

go 内存模型 并发可见性

golang 创建守护进程以及平滑重启

golang是什么语言

记一次无类型常量的思考

聊聊dapr的fswatcher

自制文件系统 — 04 hellofs 进阶 分布式加密文件系统

go time

软件测试 编写技术简历的 7 个良心建议!记得收藏!!!

golang 和 php 哪个性能更强?

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...