第一种方法:
使用"github.com/tealeg/xlsx"库
type DeviceRealTimeCityGeo struct {
Id string
Name string
At string
sex string
}
func createExcel(records []*DeviceRealTimeCityGeo) error {
var file *xlsx.File
var sheet *xlsx.Sheet
var row *xlsx.Row
var cell *xlsx.Cell
var err error
file = xlsx.NewFile()
sheet, _ = file.AddSheet("统计分析")
// Horizontals
left_align := *xlsx.DefaultAlignment()
left_align.Horizontal = "left"
left_align.Vertical = "center"
center_H_align := *xlsx.DefaultAlignment()
center_H_align.Horizontal = "center"
center_H_align.Vertical = "center"
right_align := *xlsx.DefaultAlignment()
right_align.Horizontal = "right"
right_align.Vertical = "center"
// Border
border := *xlsx.NewBorder("thin", "thin", "thin", "thin")
// title_style
title_style := xlsx.NewStyle()
font := *xlsx.NewFont(18, "SimSun")
font.Bold = true
title_style.Font = font
title_style.Alignment = center_H_align
title_style.ApplyAlignment = true
title_style.Border = border
title_style.ApplyBorder = true
// text_style
text_style := xlsx.NewStyle()
font = *xlsx.NewFont(10, "SimSun")
text_style.Font = font
text_style.Alignment = center_H_align
text_style.ApplyAlignment = true
text_style.Border = border
text_style.ApplyBorder = true
headRow1 := sheet.AddRow()
cell1 := headRow1.AddCell()
cell1.Value = "id"
cell1.SetStyle(text_style)
cell1 = headRow1.AddCell()
cell1.Value = "名称"
cell1.SetStyle(text_style)
cell1 = headRow1.AddCell()
cell1.Value = "时间"
cell1.SetStyle(text_style)
cell1 = headRow1.AddCell()
cell1.Value = "性别"
cell1.SetStyle(text_style)
// text
for i := 0; i < len(records); i++ {
row = sheet.AddRow()
cell = row.AddCell()
cell.Value = records[i].DeviceId
cell.SetStyle(text_style)
cell = row.AddCell()
cell.Value = records[i].DeviceName
cell.SetStyle(text_style)
cell = row.AddCell()
cell.Value = records[i].At
cell.SetStyle(text_style)
cell = row.AddCell()
cell.Value = records[i].Address
cell.SetStyle(text_style)
}
err = sheet.SetColWidth(1, 1, 20)
if err != nil {
return err
}
err = sheet.SetColWidth(4, 4, 20)
if err != nil {
return err
}
err = file.Save( "统计分析.xlsx")
if err != nil {
fmt.Printf(err.Error())
}
return nil
}
第二种方法
使用github.com/xuri/excelize/v2库https://xuri.me/excelize/zh-hans/
官网地址:https://xuri.me/excelize/zh-hans/
代码官网都有
f := excelize.NewFile()
// 创建一个工作表
index := f.NewSheet("Sheet1")
// 设置单元格的值
f.SetCellValue("Sheet1", "A1", "id")
f.SetCellValue("Sheet1", "B1", "name")
f.SetCellValue("Sheet1", "C1", "age")
f.SetCellValue("Sheet1", "D1", "sex")
for i := 0; i < len(records); i++ {
lint := strconv.Itoa(i+2)
fmt.Println(lint)
f.SetCellValue("Sheet1", "A" +lint, records[i].DeviceId)
f.SetCellValue("Sheet1", "B"+lint, records[i].DeviceName)
f.SetCellValue("Sheet1", "C"+lint, records[i].At)
f.SetCellValue("Sheet1", "D"+lint,records[i].Address)
}
// 设置工作簿的默认工作表
f.SetActiveSheet(index)
// 根据指定路径保存文件
if err := f.SaveAs("14.xlsx"); err != nil {
fmt.Println(err)
}