go get github.com/xuri/excelize/v2
https://github.com/qax-os/excelize
package main
import (
"fmt"
"strconv"
"github.com/xuri/excelize/v2"
)
func main() {
// 数据模拟
type row struct {
Name string
Age int
Gender string
}
excelData := make([]row, 0)
excelData = append(excelData, row{"张三", 18, "男"})
excelData = append(excelData, row{"李四", 19, "男"})
excelData = append(excelData, row{"王五", 20, "男"})
// 初始化 xlsx 操作对象
xlsx := excelize.NewFile()
// 创建一个新的 Sheet
xlsx.NewSheet("Sheet1")
// 表头
xlsx.SetCellValue("Sheet1", "A1", "姓名")
xlsx.SetCellValue("Sheet1", "B1", "性别")
xlsx.SetCellValue("Sheet1", "C1", "年龄")
// 数据填充
for index, item := range excelData {
xlsx.SetCellValue("Sheet1", "A"+strconv.Itoa((index+2)), item.Name)
xlsx.SetCellValue("Sheet1", "B"+strconv.Itoa((index+2)), item.Gender)
xlsx.SetCellValue("Sheet1", "C"+strconv.Itoa((index+2)), item.Age)
}
// 保存为电子表格
err := xlsx.SaveAs("./demo.xlsx")
if err != nil {
fmt.Println(err)
}
}