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
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM