main.go文件:
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
read() // 读excel文件
//write() // 写excel文件
//readAndWrite() // 读写excel文件
}
func read() {
f, err := excelize.OpenFile("read.xlsx")
if err != nil {
fmt.Println("excelize.OpenFile err: ", err)
return
}
defer func() {
if err := f.Close(); err != nil {
fmt.Println("excelize.CloseFile err: ", err)
}
}()
sheet := "Sheet1"
rows, err := f.GetRows(sheet)
if err != nil {
fmt.Println("f.GetRows err: ", err)
return
}
// 获取某一单元格
a1, err := f.GetCellValue(sheet, "A1")
fmt.Printf("A1:%s,err:%v\n", a1, err)
fmt.Println()
// 遍历所有行列
for i, row := range rows {
if len(row) <= 1 {
break
}
fmt.Printf("%d\t%s\t%s\t%s\n", i, row[0], row[1], row[2])
}
fmt.Println()
// 遍历所有行列
for i, row := range rows {
for j, cell := range row {
fmt.Printf("rows[%d][%d]=%s\t", i, j, cell)
}
fmt.Println()
}
}
func write() {
f := excelize.NewFile()
defer func() {
if err := f.Close(); err != nil {
fmt.Println("excelize.CloseFile err: ", err)
}
}()
sheet1 := "Sheet1"
sheet2 := "Sheet2"
index, err := f.NewSheet(sheet2)
if err != nil {
fmt.Println("f.NewSheet err: ", err)
return
}
f.SetCellValue(sheet1, "A1", "a")
f.SetCellValue(sheet1, "B2", "b")
f.SetCellValue(sheet1, "C3", "c")
f.SetCellValue(sheet2, "A3", "a")
f.SetCellValue(sheet2, "B2", "b")
f.SetCellValue(sheet2, "C1", "c")
f.SetActiveSheet(index)
if err := f.SaveAs("write.xlsx"); err != nil {
fmt.Println("excelize.SaveAs err: ", err)
}
}
func readAndWrite() {
f, err := excelize.OpenFile("read_and_write.xlsx")
if err != nil {
fmt.Println("excelize.OpenFile err: ", err)
return
}
defer func() {
if err := f.Close(); err != nil {
fmt.Println("excelize.CloseFile err: ", err)
}
}()
sheet := "Sheet1"
rows, err := f.GetRows(sheet)
if err != nil {
fmt.Println("f.GetRows err: ", err)
return
}
// 遍历所有行列
for _, row := range rows {
if len(row) <= 1 {
break
}
fmt.Println(row)
}
// 添加数据
f.SetCellValue(sheet, "D1", "备注")
f.SetCellValue(sheet, "D2", "test")
if err = f.Save(); err != nil {
fmt.Println("excelize.SaveAs err: ", err)
}
}
go.mod文件:
module excel-demo
go 1.23.0
require (
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.3 // indirect
github.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53 // indirect
github.com/xuri/excelize/v2 v2.8.1 // indirect
github.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/text v0.14.0 // indirect
)
excel效果如下:
1、read.xlsx文件
2、write.xlsx文件
3、read_and_write.xlsx文件
详见:excelize package - github.com/xuri/excelize/v2 - Go Packages