golang写入Excel并设置样式

==导入依赖==

go get github.com/xuri/excelize/v2

 

==代码样例==

复制代码
package main

import (
    "fmt"
    "github.com/xuri/excelize/v2"
)

type Fruit struct {
    Id    uint
    Name  string
    Price float64
}

type Style struct {
    Border        []Border    `json:"border"`
    Fill          Fill        `json:"fill"`
    Font          *Font       `json:"font"`
    Alignment     *Alignment  `json:"alignment"`
    Protection    *Protection `json:"protection"`
    NumFmt        int         `json:"number_format"`
    DecimalPlaces int         `json:"decimal_places"`
    CustomNumFmt  *string     `json:"custom_number_format"`
    Lang          string      `json:"lang"`
    NegRed        bool        `json:"negred"`
}

// Border 边框
type Border struct {
    Type  string `json:"type"`
    Color string `json:"color"`
    Style int    `json:"style"`
}

// Fill 填充
type Fill struct {
    Type    string   `json:"type"`
    Pattern int      `json:"pattern"`
    Color   []string `json:"color"`
    Shading int      `json:"shading"`
}

// Font 字体
type Font struct {
    Bold      bool    `json:"bold"`      // 是否加粗
    Italic    bool    `json:"italic"`    // 是否倾斜
    Underline string  `json:"underline"` // single    double
    Family    string  `json:"family"`    // 字体样式
    Size      float64 `json:"size"`      // 字体大小
    Strike    bool    `json:"strike"`    // 删除线
    Color     string  `json:"color"`     // 字体颜色
}

// Protection 保护
type Protection struct {
    Hidden bool `json:"hidden"`
    Locked bool `json:"locked"`
}

// Alignment 对齐
type Alignment struct {
    Horizontal      string `json:"horizontal"`        // 水平对齐方式
    Indent          int    `json:"indent"`            // 缩进  只要设置了值,就变成了左对齐
    JustifyLastLine bool   `json:"justify_last_line"` // 两端分散对齐,只有在水平对齐选择 distributed 时起作用
    ReadingOrder    uint64 `json:"reading_order"`     // 文字方向 不知道值范围和具体的含义
    RelativeIndent  int    `json:"relative_indent"`   // 不知道具体的含义
    ShrinkToFit     bool   `json:"shrink_to_fit"`     // 缩小字体填充
    TextRotation    int    `json:"text_rotation"`     // 文本旋转
    Vertical        string `json:"vertical"`          // 垂直对齐
    WrapText        bool   `json:"wrap_text"`         // 自动换行
}

func main() {
    createFile("testFile", "Sheet1")
}

func createFile(fileName string, sheetName string) {

    // 创建File
    file := excelize.NewFile()

    // 创建Sheet
    file.NewSheet(sheetName)

    // 定义表头样式(通过结构体方式指定)
    headStyle, _ := file.NewStyle(&excelize.Style{
        Border: []excelize.Border{
            {
                Type:  "right",
                Color: "#000000",
                Style: 2,
            },
            {
                Type:  "left",
                Color: "#000000",
                Style: 2,
            },
            {
                Type:  "top",
                Color: "#000000",
                Style: 2,
            },
            {
                Type:  "bottom",
                Color: "#000000",
                Style: 2,
            },
        }, Fill: excelize.Fill{
            // gradient: 渐变色    pattern   填充图案
            // Pattern: 1,                   // 填充样式  当类型是 pattern 0-18 填充图案  1 实体填充
            // Color:   []string{"#FF0000"}, // 当Type = pattern 时,只有一个
            Type:  "gradient",
            Color: []string{"#00F700", "#00F700"},
            // 类型是 gradient 使用 0-5 横向(每种颜色横向分布) 纵向 对角向上 对角向下 有外向内 由内向外
            Shading: 1,
        }, Font: &excelize.Font{
            Bold: true,
            // Italic: false,
            // Underline: "single",
            Size:   14,
            Family: "宋体",
            // Strike:    true, // 删除线
            Color: "#0000FF",
        }, Alignment: &excelize.Alignment{
            // 水平对齐方式 center left right fill(填充) justify(两端对齐)  centerContinuous(跨列居中) distributed(分散对齐)
            Horizontal: "center",
            // 垂直对齐方式 center top  justify distributed
            Vertical: "center",
            // Indent:     1,        // 缩进  只要有值就变成了左对齐 + 缩进
            // TextRotation: 30, // 旋转
            // RelativeIndent:  10,   // 好像没啥用
            // ReadingOrder:    0,    // 不知道怎么设置
            // JustifyLastLine: true, // 两端分散对齐,只有 水平对齐 为 distributed 时 设置true 才有效
            // WrapText:        true, // 自动换行
            // ShrinkToFit:     true, // 缩小字体以填充单元格
        }, Protection: &excelize.Protection{
            Hidden: true,
            Locked: true,
        },
        // 内置的数字格式样式   0-638  常用的 0-58  配合lang使用,因为语言不同样式不同 具体的样式参照文档
        NumFmt: 0,
        // zh-cn 中文
        Lang: "zh-cn",
        // 小数位数  只有NumFmt是 2-11 有效
        // CustomNumFmt: "",// 自定义样式  是指针,只能通过变量的方式
        DecimalPlaces: 2,
        NegRed:        true,
    })

    // 定义行样式(通过JSON格式指定)
    rowStyle, _ := file.NewStyle(`{
       "font":{
          "color":"#666666",
          "size":13,
          "family":"arial"
       },
       "alignment":{
          "vertical":"center",
          "horizontal":"center"
       }
    }`)

    // 定义内容样式
    textStyle, _ := file.NewStyle(`{
       "alignment":{
          "horizontal":"left"
       }
    }`)

    // 写入表头内容
    _ = file.SetCellValue(sheetName, "A1", "序号")
    _ = file.SetCellValue(sheetName, "B1", "名称")
    _ = file.SetCellValue(sheetName, "C1", "单价")
    // 设置表头样式
    _ = file.SetCellStyle(sheetName, "A1", "C1", headStyle)

    // 循环写入数据
    line := 1
    fruits := getFruits()
    for _, value := range fruits {
        line++
        // 写入行内容
        _ = file.SetCellValue(sheetName, fmt.Sprintf("A%d", line), value.Id)
        _ = file.SetCellValue(sheetName, fmt.Sprintf("B%d", line), value.Name)
        _ = file.SetCellValue(sheetName, fmt.Sprintf("C%d", line), value.Price)

        // 设置行样式
        _ = file.SetCellStyle(sheetName, fmt.Sprintf("A%d", line), fmt.Sprintf("C%d", line), rowStyle)
        _ = file.SetCellStyle(sheetName, fmt.Sprintf("C%d", line), fmt.Sprintf("C%d", line), textStyle)
    }

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

func getFruits() (fruits []Fruit) {
    slice := make([]Fruit, 0)
    slice = append(slice, Fruit{Id: 1, Name: "苹果", Price: 4.12})
    slice = append(slice, Fruit{Id: 2, Name: "香蕉", Price: 2.32})
    slice = append(slice, Fruit{Id: 3, Name: "西瓜", Price: 1.08})
    return slice
}
复制代码

 

posted @   大墨垂杨  阅读(2642)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2016-04-11 Storm+kafka的HelloWorld初体验
2016-04-11 KafkaOffsetMonitor使用方法
点击右上角即可分享
微信分享提示