Go 操作 excel


读 excel

package main

import (
    "fmt"

    "github.com/tealeg/xlsx"
)

func main() {
    excelFileName := "test.xls"
    xlFile, _ := xlsx.OpenFile(excelFileName)
    for _, sheet := range xlFile.Sheets {
        for _, row := range sheet.Rows {
        for _, cell := range row.Cells {
            fmt.Println(cell.String())
        }
        }
    }
}

写 excel

package main

import (
    "encoding/csv"
    "os"
)

func main() {
    f, err := os.Create("test.xls")
    if err != nil {
        panic(err)
    }
    defer f.Close()
    // 写入 utf-8 编码
    f.WriteString("\xEF\xBB\xBF")
    w := csv.NewWriter(f)
    w.Write([]string{"编号", "姓名", "年龄"})
    w.Write([]string{"1", "张三", "23"})
    w.Write([]string{"2", "李四", "24"})
    w.Write([]string{"3", "王五", "25"})
    w.Write([]string{"4", "赵六", "26"})
    w.Flush()
}
分享:

评论