欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

轻松实现Go语言导出Excel文件的简易教程

最编程 2024-02-08 16:29:23
...

在日常工作中,经常会有导出 excel 表格的功能,下面我们就简单的使用 Excelize 来导出 excel 文件。

Excelize 是 Go 语言编写的用于操作 Office Excel 文档基础库,基于 ECMA-376,ISO/IEC 29500 国际标准。可以使用它来读取、写入由 Microsoft Excel™ 2007 及以上版本创建的电子表格文档。支持 XLSX / XLSM / XLTM / XLTX 等多种文档格式,高度兼容带有样式、图片(表)、透视表、切片器等复杂组件的文档,并提供流式读写 API,用于处理包含大规模数据的工作簿。可应用于各类报表平台、云计算、边缘计算等系统。使用本类库要求使用的 Go 语言为 1.15 或更高版本。

 github: github.com/xuri/excelize

文档:https://pkg.go.dev/github.com/xuri/excelize/v2
 

安装

go get github.com/xuri/excelize

// 如果使用 Go Modules 管理软件包,可以用下面的命令来安装最新版本
go get github.com/xuri/excelize/v2

创建 Excel 文档

f := excelize.NewFile()
// 创建一个工作表 默认工作簿是Sheet1

// 设置单元格的值
// 这里设置表头
f.SetCellValue("Sheet1", "A1", "序号")
f.SetCellValue("Sheet1", "B1", "名称")

line := 1

fruits := getFruits()
// 循环写入数据
for _, v := range fruits {
   line++
   f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.ID)
   f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.Name)
}

// 保存文件
if err := f.SaveAs("fruits.xlsx"); err != nil {
   fmt.Println(err)
}

导出的文件内容是:

设置工作簿的列宽和行高

// 设置列宽
f.SetColWidth("Sheet1", "A", "C", 20)

// 设置表头行高
f.SetRowHeight("Sheet1", 1, 30)

这样并不好看,接下来继续设置单元格样式

设置单元格样式

1.设置表头字体加粗、文字水平并且垂直居中、字体、颜色。

2.设置行的字体样式默认是水平垂直居中,但是单价列的值必须靠左

下面是实现代码

// 设置表头样式
headStyleID, _ := f.NewStyle(`{
   "font":{
      "color":"#333333",
      "bold":true,
      "size":16,
      "family":"arial"
   },
   "alignment":{
      "vertical":"center",
      "horizontal":"center"
   }
}`)

// 设置行样式
rowStyleID, _ := f.NewStyle(`{
   "font":{
      "color":"#666666",
      "size":13,
      "family":"arial"
   },
   "alignment":{
      "vertical":"center",
      "horizontal":"center"
   }
}`)
f.SetCellStyle("Sheet1", "A1", "C1", headStyleID)

textLeftStyleID, _ := f.NewStyle(`{
   "alignment":{
      "horizontal":"left"
   }
}`)

for _, v := range fruits {
   line++
   f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.ID)
   f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.Name)
   f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.Price)

   // 设置行样式
   f.SetCellStyle("Sheet1", fmt.Sprintf("A%d", line), fmt.Sprintf("C%d", line), rowStyleID)
   f.SetCellStyle("Sheet1", fmt.Sprintf("C%d", line), fmt.Sprintf("C%d", line), textLeftStyleID)
}

结果:

表格数据源

type fruit struct {
   ID    uint
   Name  string
   Price float64
}

func getFruits() []*fruit {
   return []*fruit{
      &fruit{
         ID:    1,
         Name:  "苹果",
         Price: 8,
      },
      &fruit{
         ID:    2,
         Name:  "雪梨",
         Price: 5,
      },
      &fruit{
         ID:    3,
         Name:  "香蕉",
         Price: 3,
      },
   }
}

简单粗暴的贴代码。。。希望有点帮助