使用第三方库
https://github.com/qax-os/excelize
安装:
go get github.com/xuri/excelize
- If your packages are managed using Go Modules, please install with following command.
go get github.com/xuri/excelize/v2
工程下 go.mod 文件
------------------------------------------------------------------------------- module golang_lan_tool go 1.19 require github.com/xuri/excelize/v2 v2.6.0
----------------------------------------------------------------------------------------------------------------------------
以下是官方使用例子
//---写
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
f := excelize.NewFile()
// Create a new sheet.
index := f.NewSheet("Sheet2")
// Set value of a cell.
f.SetCellValue("Sheet2", "A2", "Hello world.")
f.SetCellValue("Sheet1", "B2", 100)
// Set active sheet of the workbook.
f.SetActiveSheet(index)
// Save spreadsheet by the given path.
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
//--读取
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
defer func() {
// Close the spreadsheet.
if err := f.Close(); err != nil {
fmt.Println(err)
}
}()
// Get value from cell by given worksheet name and axis.
cell, err := f.GetCellValue("Sheet1", "B2")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(cell)
// Get all the rows in the Sheet1.
rows, err := f.GetRows("Sheet1")
if err != nil {
fmt.Println(err)
return
}
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "\t")
}
fmt.Println()
}
}
本文介绍了如何使用Go语言的第三方库excelize进行Excel文件的读写操作。通过示例代码展示了创建新工作表、设置单元格值、读取单元格值以及读取整行数据的基本用法,帮助开发者快速掌握该库的使用。
3937

被折叠的 条评论
为什么被折叠?



