1、导入xlsx直接生成Excel:
go get github.com/tealeg/xlsx
- 如果在get包时长时间没有反应,那可以直接从我的百度云下载 xlsx 包,之后直接放在你项目的 github.com 文件夹下就可以了
https://pan.baidu.com/s/1T-RsQ6lyP2bw330tD1svgQ
package main
import "github.com/tealeg/xlsx"
func main() {
file := xlsx.NewFile()
sheet,err := file.AddSheet("sheet1")
if err != nil {
panic(err)
}
row := sheet.AddRow()
row.SetHeightCM(1) //设置每行的高度
cell := row.AddCell()
cell.Value = "haha"
cell = row.AddCell()
cell.Value = "1234567"
err = file.Save("file.xlsx")
if err != nil {
panic(err)
}
}
-
效果如下:
2、简单封装:
package xlsxtool
import (
"github.com/tealeg/xlsx"
"errors"
)
type XlsxRow struct {
Row *xlsx.Row
Data []string
}
func NewRow(row *xlsx.Row,data []string) *XlsxRow {
return &XlsxRow{
Row:row,
Data:data,
}
}
func (row *XlsxRow) SetRowTitle() error {
return generateRow(row.Row,row.Data)
}
func (row *XlsxRow) GenerateRow() error {
return generateRow(row.Row,row.Data)
}
func generateRow(row *xlsx.Row,rowStr []string) error {
if rowStr == nil {
return errors.New("no data to generate xlsx!")
}
for _,v := range rowStr {
cell := row.AddCell()
cell.SetString(v)
}
return nil
}
- 调用:
package peopleExcel
import (
"test/mode"
"test/xlsxtool"
"fmt"
"github.com/tealeg/xlsx"
"time"
)
func GeneratePeopleExcel(peo []mode.Person) (error, bool) {
t1 := time.Now()
defer func() {
fmt.Println(time.Since(t1))
}()
t := make([]string, 0)
t = append(t, "姓名")
t = append(t, "性别")
t = append(t, "年龄")
t = append(t, "电话")
t = append(t, "婚配")
t = append(t, "现居地")
file := xlsx.NewFile()
sheet, err := file.AddSheet("sheet")
if err != nil {
return err, false
}
titleRow := sheet.AddRow()
xlsRow := xlsxtool.NewRow(titleRow, t)
err = xlsRow.SetRowTitle()
if err != nil {
return err, false
}
for _, v := range peo {
currentRow := sheet.AddRow()
tmp := make([]string, 0)
tmp = append(tmp, v.Name)
tmp = append(tmp, v.Gender)
tmp = append(tmp, v.Age)
tmp = append(tmp, v.Tel)
tmp = append(tmp, v.Marry)
tmp = append(tmp, v.Address)
xlsRow := xlsxtool.NewRow(currentRow, tmp)
err := xlsRow.GenerateRow()
if err != nil {
return err, false
}
}
err = file.Save("./Excel/人员信息.xlsx")
if err != nil {
return err, false
}
return nil, true
}
-
效果如下:
-
写完封装后,我仔细想了想,其实不用封装,可以直接遍历,封装的意义何在?(此处应该有个傻笑的表情 ^ - ^)。