基于数据生成 Excel 文档是一个很常见的需求,本文将介绍如何使用 Go 的 Excelize 库去生成 Excel 文档,以及一些具体场景下的代码实现。

关于 Excelize 库

Excelize

性能对比

下图是一些主要的开源 Excel 库在生成 12800*50 纯文本矩阵时的性能对比(OS: macOS Mojave version 10.14.4, CPU: 3.4 GHz Intel Core i5, RAM: 16 GB 2400 MHz DDR4, HDD: 1 TB),包括 Go、Python、Java、PHP 和 NodeJS。

安装

v2.4.0
go get github.com/360EntSecGroup-Skylar/excelize/v2

创建 Excel 文档

NewSheetSheet2Sheet1SetCellValueSheet2A2Sheet1B2SetActiveSheetSheet2SaveAs
package main

import (
    "fmt"

    "github.com/360EntSecGroup-Skylar/excelize/v2"
)

func main() {
    f := excelize.NewFile()
    // 创建一个工作表
    index := f.NewSheet("Sheet2")
    // 设置单元格的值
    f.SetCellValue("Sheet2", "A2", "Hello world.")
    f.SetCellValue("Sheet1", "B2", 100)
    // 设置工作簿的默认工作表
    f.SetActiveSheet(index)
    // 根据指定路径保存文件
    if err := f.SaveAs("Book1.xlsx"); err != nil {
        fmt.Println(err)
    }
}

实际场景复现

创建工作表

工作表名称是大小写敏感的:

index := f.NewSheet("Sheet2")

删除默认创建的工作表

Sheet1
f.DeleteSheet("Sheet1")

合并单元格

Sheet1F1:I2
excel.MergeCell("Sheet1", "F1", "I2")

单元格样式

ExcelizeNewStyleSetCellStyle
// 通过给定的样式格式 JSON 或结构体的指针创建样式并返回样式索引。
// 请注意,颜色需要使用 RGB 色域代码表示。
style, err := f.NewStyle(`{
    "border": [
    {
        "type": "left",
        "color": "0000FF",
        "style": 3
    },
    {
        "type": "top",
        "color": "00FF00",
        "style": 4
    },
    {
        "type": "bottom",
        "color": "FFFF00",
        "style": 5
    },
    {
        "type": "right",
        "color": "FF0000",
        "style": 6
    },
    {
        "type": "diagonalDown",
        "color": "A020F0",
        "style": 7
    },
    {
        "type": "diagonalUp",
        "color": "A020F0",
        "style": 8
    }]
}`)
if err != nil {
    fmt.Println(err)
}
err = f.SetCellStyle("Sheet1", "D7", "D7", style)

文字水平居中

Alignment
type Alignment struct {
    Horizontal      string `json:"horizontal"`
    Indent          int    `json:"indent"`
    JustifyLastLine bool   `json:"justify_last_line"`
    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"`
}
Horizontalcenter
style, err := f.NewStyle(`{"alignment":{"horizontal":"center"}}`)
if err != nil {
    fmt.Println(err)
}
err = excel.SetCellStyle("Sheet1", "B1", "B1", style)

给单元格设置纯色填充

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

Style 结构体

borderalignmentStyle
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"`
}
相关推荐:Go视频教程