Go to operate Excel tool excelize

Continue to create, accelerate growth! This is the 7th day of my participation in the "Nuggets Daily New Plan · October Update Challenge", click to view the details of the event

foreword

Some requirements in the development need to be manipulated through the program excel, such as exporting excel, importing excel, excelinserting pictures, tables and charts into the document. ExcelizeThe above requirements can be easily met. This article mainly summarizes the use of Excelize, and I hope it will help you. help. If there are any mistakes or not considered completely, please let me know.

Introduction to Excelize

Excelize is a class library written in Go language for operating Office Excel documents. It can be used to read and write Excel files. It also supports inserting pictures, icons, and tool functions into Excel. It has relatively complete functions. The demand is completely sufficient, don't talk nonsense, just start working.

Install

go get github.com/xuri/excelize
# 如果你是通过Go Module管理的包,执行以下安装
go get github.com/xuri/excelize/v2
复制代码

Export Excel document

package main

import (
    "fmt"

    "github.com/xuri/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("export.xlsx"); err != nil {
        fmt.Println(err)
    }
}
复制代码

Read Excel documents

package main

import (
    "fmt"

    "github.com/xuri/excelize/v2"
)

func main() {
    f, err := excelize.OpenFile("Book1.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer func() {
        if err := f.Close(); err != nil {
            fmt.Println(err)
        }
    }()
    // 获取工作表中指定单元格的值
    cell, err := f.GetCellValue("Sheet1", "B2")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(cell)
    // 获取 Sheet1 上所有单元格
    rows, err := f.GetRows("Sheet1")
    if err != nil {
        fmt.Println(err)
        return
    }
    for _, row := range rows {
        for _, colCell := range row {
            fmt.Print(colCell, "\t")
        }
        fmt.Println()
    }
}
复制代码

summary

In this article, I briefly introduce how Go uses Excelize to import and export Excel. Excelize is a basic library written in Go language for manipulating Office Excel documents. It can be used to read and write Excel documents, and also supports to Inserting pictures, icons, and tool functions into Excel has relatively complete functions and is completely sufficient for basic needs.

There is a Chinese document on the Internet that introduces the use of excelize in detail. The summary is quite comprehensive. The address is: xuri.me/excelize/zh…

Guess you like

Origin juejin.im/post/7150436282575880200