Golang中使用Excelize导出表格封装,可设置行高图片根据行高可开启自动压缩。

3838人浏览 2021-03-19

Golang中使用Excelize导出表格封装,可设置行高图片根据行高可开启自动压缩。

1.使用之前需要安装Excelize

使用最新版本 Excelize 要求您使用的 Go 语言为 1.10 或更高版本。

  • 安装命令
go get github.com/360EntSecGroup-Skylar/excelize
  • 如果您使用 Go Modules 管理软件包,请使用下面的命令来安装最新版本。
go get github.com/360EntSecGroup-Skylar/excelize/v2

 

设置单元格格式设置行高列宽等等参考官以下方文档,功能非常丰富!

Excelize中文文档:

https://xuri.me/excelize/zh-hans/

 

封装如下:

package utils

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"os"
	"strings"
	"yinolink/common/config"
)

//AdminExcel 导出表格 参数
// 若导出图片 则HeadKey要以'IMG_'开头
type AdminExcel struct {
	Name string  //文件名称
	Suffix   string //导出格式
	HeadKey []string //首行标题
	DataTitle []string //数据key
	SavePath string 	//保存文件路径
	SheetName string //	表名  默认 Sheet1
	RowHeight int  //行高  默认 50
	Scale   float32 //图片宽高压缩比例 默认 0.2
	AutoScale bool //是否开启自动判断图片压缩比例,开启后上面Scale无效 ,会读取图片占用一定资源
}
//ExcelDatA 导出数据 行格式
var ExcelData []map[string]interface{}

//ExportExcel 导出表格
func (this *AdminExcel) ExportExcel(data []map[string]interface{}) (filePath string, err error) {
	f := excelize.NewFile()
	// 创建一个工作表
	sheetName := "Sheet1"
	if this.SheetName != ""{
		sheetName = this.SheetName
	}
	index := f.NewSheet(sheetName)
	if this.RowHeight == 0 {
		this.RowHeight = 50  //默认50
	}
	if this.Scale == 0 {
		this.Scale = 0.2
	}
	if len(this.HeadKey) != len(this.DataTitle){
		config.LoggerGlobal.Error("param info err ")
		return
	}

	//设置表头
	for i,  title := range this.DataTitle{
		cellNum := fmt.Sprintf("%c1",65+i)
		_ = f.SetCellValue("Sheet1", cellNum, title)
		_ = f.SetRowHeight("Sheet1", 1+i, 40)
	}

	// 设置单元格的值
	for i , rows := range data {  //一行

		for num, key := range this.HeadKey { //每列
			line := fmt.Sprintf("%c%d",65+num,i+2)

			if strings.Index(key,"IMG_") == -1 {  //正常值
				_ = f.SetCellValue("Sheet1", line, rows[key])
			}else{ //图片
				link := fmt.Sprintf("%s", rows[key])
				format := ``
				if this.AutoScale {
					//获取图片宽高
					file ,_ := os.Open(link)
					img ,_,_ := image.Decode(file)
					_ = file.Close()
					b := img.Bounds()
					yScale :=  fmt.Sprintf("%f", float64(this.RowHeight) / float64(b.Max.Y))
					format = `{  "x_scale": `+ yScale+`, "y_scale": `+ yScale+` }`
				}else{
					format = `{  "x_scale": `+ fmt.Sprintf("%f",this.Scale) +`, "y_scale": `+ fmt.Sprintf("%f",this.Scale) +` }`
				}

				_ = f.AddPicture("Sheet1", line, link, format )
			}
		}
		//设置行高
		_ = f.SetRowHeight("Sheet1", 2+i, float64(this.RowHeight))
	}

	// 设置工作簿的默认工作表
	f.SetActiveSheet(index)

	fileName := this.SavePath + this.Name + this.Suffix

	// 根据指定路径保存文件
	if err = f.SaveAs(fileName); err != nil {
		return "", err
	}
	return fileName, err


}

//测试使用 
func TestExport()  {

	//设置首行标题
	dataTitle := [3]string{
		"标题",
		"价格",
		"图片",
	}
	//设置数据key
	headKey := [3]string{
		"title",
		"price",
		"IMG_test",
	}
	Excel := &AdminExcel{
		Name: "test",
		Suffix: ".xlsx",
		HeadKey: headKey[:],
		DataTitle: dataTitle[:],
		AutoScale: true,
	}
	//data := make([]map[string]interface{},0)
	data := ExcelData

	data = append(data,
		map[string]interface{}{"title":"海带","price":"19.90","IMG_test":"123.png"},
		map[string]interface{}{"title":"白菜","price":"9.90","IMG_test":"logo-mate.png"},
		map[string]interface{}{"title":"萝卜","price":"4.90","IMG_test":"logo-mate.png"},
	)
	file , err := Excel.ExportExcel(data)
	fmt.Println(err)
	fmt.Println(file)
}

导出效果:

资源原创,禁止转载。

 

 

推荐文章

GORM 自定义结构体关联的数据库表名称和自定义结构体字段对应的数据表字段名
2021-02-23
KChatRoom在线多人聊天室,项目是使用Websocket和Gin框架基于Golang开发的在线聊天室
2021-05-17
Gin框架下获取所有路由信息
2021-07-14
搜索文章