golang利用反射写入excel的简单工具类

golang利用反射写入excel的简单工具类

工具类源码

package excel

import (
	"errors"
	"fmt"
	"github.com/tealeg/xlsx"
	"os"
	"reflect"
	"strconv"
	"strings"
	"zonst/qipai/api/searchscript/infoqueryscript/log"
)

func WriteExcel(filePath string, objs interface{}) error {
	kind := reflect.TypeOf(objs).Kind()
	if kind != reflect.Slice && kind != reflect.Array {
		return errors.New("need slice or array")
	}

	file := xlsx.NewFile()
	sheet, err := file.AddSheet("sheet")
	if err != nil {
		log.Errorf(err.Error())
		return err
	}

	values := reflect.ValueOf(objs)
	for i := 0; i < values.Len(); i++ {
		value := values.Index(i)
		if value.Kind() == reflect.Ptr {
			value = value.Elem()
		}

		row := sheet.AddRow()
		if i == 0 {
			//新增表头
			valType := value.Type()
			for j := 0; j < value.NumField(); j++ {
				row.AddCell().SetValue(valType.Field(j).Tag.Get("excel"))
			}

			row = row.Sheet.AddRow()
			for v := 0; v < value.NumField(); v++ {
				field := value.Field(v)
				val := objToString(field)
				row.AddCell().SetValue(val)
			}
			continue
		}

		for v := 0; v < value.NumField(); v++ {
			field := value.Field(v)
			val := objToString(field)
			row.AddCell().SetValue(val)
		}
	}

	return saveExcel(filePath, file)
}

func objToString(field reflect.Value) string {
	switch field.Type().Kind() {
	case reflect.Int:
		return strconv.Itoa(int(field.Int()))
	case reflect.Int32:
		return strconv.Itoa(int(field.Int()))
	case reflect.Int64:
		return strconv.Itoa(int(field.Int()))
	case reflect.Float32:
		return fmt.Sprintf("%v", field.Float())
	case reflect.Float64:
		return fmt.Sprintf("%v", field.Float())
	case reflect.Bool:
		return fmt.Sprintf("%v", field.Bool())
	case reflect.String:
		return field.String()
	default:
		return field.String()
	}
}

func saveExcel(filePath string, file *xlsx.File) error {
	//取出文件夹目录
	if strings.Contains(filePath, "/") {
		index := strings.LastIndex(filePath, "/")
		dir := filePath[0:index]
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			log.Errorf("MkdirAll失败 err:%v", err)
			return err
		}
	}

	err := file.Save(filePath)
	if err != nil {
		log.Errorf("保存excel失败 err:%v", err)
		return err
	}
	return nil
}

使用方法

package main

import "zonst/qipai/api/searchscript/infoqueryscript/excel"

type People struct {
	Name string `excel:"姓名"`
	Age  int    `excel:"年龄"`
}

func main() {
	arr := []People{
		{
			Name: "张三",
			Age:  18,
		},
		{
			Name: "李四",
			Age:  20,
		},
	}

	err := excel.WriteExcel("/Users/zonst/Downloads/用户信息.xlsx", arr)
	if err != nil {
		panic(err)
	}
}

效果图:
golang利用反射写入excel的简单工具类

上一篇:Go使用反射递归复制结构体


下一篇:golang 11. pair reflect struct_tag json