需求
业务上经常会遇到要导出查询结果的Excel
文档,我平时会用excelize
包来做。
入门
下载
安装
1
| go get github.com/360EntSecGroup-Skylar/excelize
|
更新
1
| go get -u github.com/360EntSecGroup-Skylar/excelize
|
创建Excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package main import ( "fmt" "github.com/360EntSecGroup-Skylar/excelize" ) func main() { f := excelize.NewFile() index := f.NewSheet("Sheet2") f.MergeCell("Sheet1", "A1", "J1") f.SetCellValue("Sheet2", "A2", "Hello world.") f.SetCellValue("Sheet1", "B2", 100) f.SetActiveSheet(index) err := f.SaveAs("./Book1.xlsx") if err != nil { fmt.Println(err) } }
|
读取Excel
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
| package main import ( "fmt" "github.com/360EntSecGroup-Skylar/excelize" ) func main() { f, err := excelize.OpenFile("./Book1.xlsx") if err != nil { fmt.Println(err) return } cell, err := f.GetCellValue("Sheet1", "B2") if err != nil { fmt.Println(err) return } fmt.Println(cell) rows, err := f.GetRows("Sheet1") for _, row := range rows { for _, colCell := range row { fmt.Print(colCell, "\t") } fmt.Println() } }
|
参考资料
Excelize v2.0 中文文档