【Golang】基于 excelize 的 Excel 工具包

目录

    • 1. 安装excelize库
    • 2. Excel工具代码
      • 2.1 初始化Excel对象
      • 2.2. 常用操作
        • 2.2.1 设置窗格冻结
        • 2.2.2 设置工作表名称
        • 2.2.3 创建工作表
        • 2.2.4 设置单元格值
        • 2.2.5 设置单元格样式
        • 2.2.6 合并单元格
        • 2.2.7 设置行高和列宽
    • 3.使用示例
    • 4.完整代码
    • 5.总结

 在日常的开发中,我们经常需要对Excel进行各种各样的操作,比如生成Excel报表、对Excel数据进行处理等。在Golang中,有一个非常好用的库——excelize,它支持对Excel文件的创建、读取、修改等操作。

1. 安装excelize库

首先,我们需要安装excelize库。在终端中执行以下命令:

go get github.com/xuri/excelize/v2

2. Excel工具代码

2.1 初始化Excel对象

 在使用excelize之前,我们需要初始化一个Excel对象。这个对象包含了Excel文件的信息,以及一些常用的样式。我们可以定义一个Excel结构体,然后创建一个ExcelInit函数来初始化这个结构体。

package utils
import ("github.com/xuri/excelize/v2"
)
var DEFAULT_ROW_HEIGHT = float64(25)
var DEFAULT_COLUMN_WIDTH = float64(18)
// Excel对象结构体
type Excel struct {File          *excelize.FileTitleStyle    int // 标题样式HeadStyle     int // 头样式ContentStyle  int // 主体样式ContentStyle2 int // 主体样式, 带背景色
}
// 初始化一个Excel对象结构体
func ExcelInit() (e *Excel) {e = &Excel{}// excel构建e.File = excelize.NewFile()// 初始化样式e.getTitleRowStyle()e.getHeadRowStyle()e.getDataRowStyle()return e
}

2.2. 常用操作

2.2.1 设置窗格冻结

在Excel中,我们可以通过设置窗格冻结来固定某些行和列,使得它们在滚动时保持可见。在excelize中,我们可以使用SetPaneFreeze方法来实现这个功能。

// 设置窗格冻结
func (e *Excel) SetPaneFreeze(sheet string, col int, row int) error {cell, err := excelize.CoordinatesToCellName(col+1, row+1)if err != nil {return err}return e.File.SetPanes(sheet, &excelize.Panes{Freeze: true, Split: false, XSplit: col, YSplit: row, TopLeftCell: cell, ActivePane: "bottomLeft"})
}
2.2.2 设置工作表名称

我们可以使用SetSheetName方法来设置工作表的名称。

// 设置工作表名称
func (e *Excel) SetSheetName(index int, sheetName string) error {sheet := e.File.GetSheetName(index)return e.File.SetSheetName(sheet, sheetName)
}

使用ChangeSheetName修改工作表名称

func (e *Excel) ChangeSheetName(sheet string, newSheetName string) error {index, err := e.File.GetSheetIndex(sheet)if err != nil {return err}if index >= 0 {err = e.File.SetSheetName(sheet, newSheetName)}return err
}
2.2.3 创建工作表

使用CreateSheet方法可以创建一个新的工作表。如果工作表已存在,则返回该工作表的索引;如果不存在,则创建新的工作表并返回其索引。

// 创建工作表
func (e *Excel) CreateSheet(sheet string) (int, error) {index, err := e.File.GetSheetIndex(sheet)if err != nil {return index, err}if index < 0 {index, err = e.File.NewSheet(sheet)}return index, err
}
2.2.4 设置单元格值

使用SetCellValue方法可以在指定的工作表中设置某个单元格的值。

// 设置单元格值
func (e *Excel) SetCellValue(sheet string, col int, row int, value interface{}) error {cell, err := excelize.CoordinatesToCellName(col, row)if err != nil {return err}return e.File.SetCellValue(sheet, cell, value)
}
2.2.5 设置单元格样式

使用SetCellStyle方法可以为指定工作表中的单元格设置样式。

// 设置单元格样式
func (e *Excel) SetCellStyle(sheet string, col int, row int, styleID int) error {cell, err := excelize.CoordinatesToCellName(col, row)if err != nil {return err}return e.File.SetCellStyle(sheet, cell, cell, styleID)
}

使用SetCellsStyle方法可以为指定工作表范围内的单元格设置样式。

func (e *Excel) SetCellsStyle(sheet string, startCol int, startRow int, endCol int, endRow int, styleID int) error {startCell, err := excelize.CoordinatesToCellName(startCol, startRow)if err != nil {return err}endCell, err := excelize.CoordinatesToCellName(endCol, endRow)if err != nil {return err}return e.File.SetCellStyle(sheet, startCell, endCell, styleID)
}

使用SetCellHeadStyle设置单元格为头样式

func (e *Excel) SetCellHeadStyle(sheet string, col int, row int) error {return e.SetCellStyle(sheet, col, row, e.HeadStyle)
}

使用SetCellsHeadStyle设置范围单元格为头样式

func (e *Excel) SetCellsHeadStyle(sheet string, startCol int, startRow int, endCol int, endRow int) error {return e.SetCellsStyle(sheet, startCol, startRow, endCol, endRow, e.HeadStyle)
}

使用SetCellTitleStyle设置单元格为标题样式

func (e *Excel) SetCellTitleStyle(sheet string, col int, row int) error {return e.SetCellStyle(sheet, col, row, e.TitleStyle)
}

使用SetCellsTitleStyle设置范围单元格为标题样式

func (e *Excel) SetCellsTitleStyle(sheet string, startCol int, startRow int, endCol int, endRow int) error {return e.SetCellsStyle(sheet, startCol, startRow, endCol, endRow, e.TitleStyle)
}

使用SetCellContentStyle设置单元格为正文样式

func (e *Excel) SetCellContentStyle(sheet string, col int, row int) error {return e.SetCellStyle(sheet, col, row, e.ContentStyle)
}

使用SetCellsContentStyle设置范围单元格为正文样式

func (e *Excel) SetCellsContentStyle(sheet string, startCol int, startRow int, endCol int, endRow int) error {return e.SetCellsStyle(sheet, startCol, startRow, endCol, endRow, e.ContentStyle)
}
2.2.6 合并单元格

使用MergeCells方法可以在指定的工作表中合并一个矩形区域的单元格。

// 合并单元格
func (e *Excel) MergeCells(sheet string, startCol, startRow, endCol, endRow int) (err error) {startCell, err := excelize.CoordinatesToCellName(startCol, startRow)if err != nil {return err}endCell, err := excelize.CoordinatesToCellName(endCol, endRow)if err != nil {return err}return e.File.MergeCell(sheet, startCell, endCell)
}
2.2.7 设置行高和列宽

使用SetRowHeight 设置行高

func (e *Excel) SetRowHeight(sheet string, row int, height float64) error {return e.File.SetRowHeight(sheet, row, height)
}

使用SetRowsHeight设置多行高度

func (e *Excel) SetRowsHeight(sheet string, startRow int, endRow int, height float64) (err error) {for i := startRow; i <= endRow; i++ {err = e.File.SetRowHeight(sheet, i, height)if err != nil {return}}return
}

使用SetColWidth设置列宽

func (e *Excel) SetColWidth(sheet string, col int, width float64) error {cell, err := excelize.ColumnNumberToName(col)if err != nil {return err}return e.File.SetColWidth(sheet, cell, cell, width)
}

使用SetColsWidth 设置多列宽度

func (e *Excel) SetColsWidth(sheet string, startCol int, endCol int, width float64) (err error) {startColName, err := excelize.ColumnNumberToName(startCol)if err != nil {return}endColName, err := excelize.ColumnNumberToName(endCol)if err != nil {return}return e.File.SetColWidth(sheet, startColName, endColName, width)
}

使用SetColDefaultWidth 设置列为默认宽度

func (e *Excel) SetColDefaultWidth(sheet string, col int) error {return e.SetColWidth(sheet, col, DEFAULT_COLUMN_WIDTH)
}

使用SetColDefaultWidth 设置多列为默认宽度

func (e *Excel) SetColsDefaultWidth(sheet string, startcol, endcol int) error {return e.SetColsWidth(sheet, startcol, endcol, DEFAULT_COLUMN_WIDTH)
}

使用SetRowDefaultHeight 设置行为默认高度

func (e *Excel) SetRowDefaultHeight(sheet string, row int) error {return e.SetRowHeight(sheet, row, DEFAULT_ROW_HEIGHT)
}

使用SetRowsDefaultHeight 设置多行为默认高度

func (e *Excel) SetRowsDefaultHeight(sheet string, startRow, endRow int) (err error) {return e.SetRowsHeight(sheet, startRow, endRow, DEFAULT_ROW_HEIGHT)
}

3.使用示例

package mainimport ("fmt""github.com/your_project_path/utils"
)func main() {// 初始化Excel对象e := utils.ExcelInit()// 创建一个新的工作表sheetName := "Sheet1"e.CreateSheet(sheetName)// 修改工作表名称e.ChangeSheetName(sheetName, "New Sheet Name")// 设置单元格值e.SetCellValue("New Sheet Name", 1, 1, "Hello World")// 设置单元格样式e.SetCellsTitleStyle("New Sheet Name", 1, 1, 5, 1)// 合并单元格e.MergeCells("New Sheet Name", 1, 1, 5, 1)// 设置行高e.SetRowDefaultHeight("New Sheet Name", 1)// 设置列宽e.SetColsDefaultWidth("New Sheet Name", 1, 5)// 设置单元格样式e.SetCellsTitleStyle("New Sheet Name", 1, 2, 5, 2)// 设置单元格数值for i := 0; i < 5; i++ {e.SetCellValue("New Sheet Name", i+1, 2, i)}// 设置冻结首行e.SetPaneFreeze("New Sheet Name", 0, 1)// 保存文件e.File.SaveAs("output.xlsx")
}

以上示例忽略error返回值,实际使用需要考虑error不为nil的情况。

输出结果:
在这里插入图片描述
请添加图片描述

4.完整代码


 [下载链接]

5.总结

 本文详细介绍了Golang中excelize库的基本使用方法,包括初始化Excel对象、常用操作等。通过这些方法,我们可以轻松地对Excel进行各种各样的操作。在实际开发中,我们可以根据自己的需求,灵活运用这些方法,实现复杂的Excel操作。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/687242.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

杰发科技AC7801——ADC之Bandgap和内部温度计算

0. 参考 电流模架构Bandgap设计与仿真 bandgap的理解&#xff08;内部带隙电压基准&#xff09; ​ ​ 虽然看不懂这些公式&#xff0c;但是比较重要的一句应该是这个&#xff1a;因为传统带隙基准的输出值为1.2V ​ 1. 使用 参考示例代码。 40002000是falsh控制器寄…

c++opencv Project3 - License Plate Detector

俄罗斯车牌识别案例&#xff1a;实时识别车牌&#xff0c;并且读取到指定文件夹中。 惯例先展示结果图&#xff1a; 对于摄像头读取图片进行车牌匹配&#xff0c;原理和人脸识别其实是一致的。 利用训练好的模型进行匹配即可。可参考&#xff1a; 对视频实现人脸识别-CSDN博…

C语言---使用共用体将double型经纬度存储到无符号数组中

1.在上报经纬度时由于数据协议限制需要将double型数据存储到无符号数组中&#xff0c;下边是写了一个简单C程序进行验证&#xff1b; 2.代码示例如下 #include <stdio.h> typedef union {float data;unsigned char arr[4]; } my_data;int main() {my_data test_data {…

滑动窗口篇: 长度最小子数组|无重复字符最长字串

目录 1、滑动窗口算法 1.1 核心概念 1.2 基本步骤 1.3 应用场景 1.4 优势 2. leetcode 209 长度最小子数组 暴力解题思路&#xff1a; 滑动窗口思路&#xff1a; 3、无重复字符的最长子串 暴力解题思路&#xff1a; 滑动窗口思路&#xff1a; 1、滑动窗口算法 滑动…

uniapp开发微信小程序,选择地理位置uni.chooseLocation

<view click"toCommunity">点击选择位置</view>toCommunity() {const that thisuni.getSetting({success: (res) > {const status res.authSetting// 如果当前设置是&#xff1a;不允许&#xff0c;则需要弹框提醒客户&#xff0c;需要前往设置页面…

主机通过带光发端和ops接收端控制屏串口调试记录

场景就是主机电脑使用cutecom通过光纤口再到ops接收端从而控制屏过程 光纤口有个发送端波特率&#xff0c;Ops有接收端波特率&#xff0c;屏有自己的波特率&#xff0c;主机电脑可以通过发串口指令去设置发送端波特率和ops接收端波特率。因为主机只有一个&#xff0c;屏有多种…

概念解析 | ROC曲线:评估分类模型

注1:本文系"概念解析"系列之一,致力于简洁清晰地解释、辨析复杂而专业的概念。本次辨析的概念是:ROC曲线的含义和绘制 概念解析 | ROC曲线:评估分类模型 第一部分:通俗解释 在我们的日常生活中,经常会遇到需要做出判断和选择的情况。比如,当你收到一封邮件时…

OmniPlan Pro 4 for Mac中文激活版:项目管理的新选择

OmniPlan Pro 4 for Mac作为一款专为Mac用户设计的项目管理软件&#xff0c;为用户提供了全新的项目管理体验。其直观易用的界面和强大的功能特性&#xff0c;使用户能够轻松上手并快速掌握项目管理要点。 首先&#xff0c;OmniPlan Pro 4 for Mac支持自定义视图&#xff0c;用…

springboot增删改查

我的记录 RestController RequestMapping("/user") public class UserController {Autowiredprivate UserService userService;GetMapping("/list")public List<User> list(){return userService.list();}//新增PostMapping("/save")publi…

读天才与算法:人脑与AI的数学思维笔记24_预测性文本生成器

1. 起源 1.1. 人类讲故事可能起源于“假如……”这种问答结构 1.2. 讲故事是人类做安全试验的一种方式 1.2.1. 如果你问一个人“假如……”&#xff0c;其实是在探索你的行为对他可能带来的影响 1.3. 最早出现的故事极有可能就源自我们对在周遭混乱的环境中寻找某种秩序的渴…

【RocketMQ问题总结-2】

RocketMQ 消息持久化 Broker通过底层的Netty服务器获取到一条消息后&#xff0c;会把这条消息的内容写入到一个CommitLog文件里去&#xff08;一个Broker进程就只有一个CommitLog文件&#xff0c;也就是说这个Broker上所有Topic的消息都会写入这个文件&#xff09;。 同时&…

贪心算法----最大数

今日题目&#xff1a;leetcode179------点击跳转题目 分析&#xff1a; 要把这些数组组成最大的数&#xff0c;首先我们把数字转化为字符串&#xff0c;根据自定义的排序规则把这些字符串字数排列&#xff0c;再用一个字符串接受这些字符串数字拼接成最大的字符串数字 排序规则…