Go-Excelize API源码阅读(二十五)——GetSheetName、GetSheetIndex、GetSheetMap

84 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第14天,点击查看活动详情

Go-Excelize API源码阅读(二十五)——GetSheetName、GetSheetIndex、GetSheetMap

一、Go-Excelize简介

Excelize 是 Go 语言编写的用于操作 Office Excel 文档基础库,基于 ECMA-376,ISO/IEC 29500 国际标准。可以使用它来读取、写入由 Microsoft Excel™ 2007 及以上版本创建的电子表格文档。支持 XLAM / XLSM / XLSX / XLTM / XLTX 等多种文档格式,高度兼容带有样式、图片(表)、透视表、切片器等复杂组件的文档,并提供流式读写 API,用于处理包含大规模数据的工作簿。可应用于各类报表平台、云计算、边缘计算等系统。使用本类库要求使用的 Go 语言为 1.15 或更高版本。

二、 GetSheetName(index int)

func (f *File) GetSheetName(index int) string

根据给定的工作表索引获取工作表名称,如果工作表不存在将返回空字符。

直接来看源代码:

// GetSheetName provides a function to get the sheet name of the workbook by
// the given sheet index. If the given sheet index is invalid, it will return
// an empty string.
func (f *File) GetSheetName(index int) (name string) {
	for idx, sheet := range f.GetSheetList() {
		if idx == index {
			name = sheet
			return
		}
	}
	return
}

代码逻辑很简单,直接遍历文件的工作表,然后判断工作表的idx是不是我们要找的index,如果是的话,将同时获取到的sheet赋值给name,然后返回。

三、GetSheetIndex(sheet string)

func (f *File) GetSheetIndex(sheet string) int

根据给定的工作表名称获取该工作表的索引,如果工作表不存在将返回 -1。

获取到的索引可以在设置工作簿默认工作表时,作为调用 SetActiveSheet() 函数的参数使用。

直接来看源代码:

// GetSheetIndex provides a function to get a sheet index of the workbook by
// the given sheet name, the sheet names are not case-sensitive. If the given
// sheet name is invalid or sheet doesn't exist, it will return an integer
// type value -1.
func (f *File) GetSheetIndex(name string) int {
	for index, sheet := range f.GetSheetList() {
		if strings.EqualFold(sheet, trimSheetName(name)) {
			return index
		}
	}
	return -1
}

代码逻辑很简单,先遍历工作表列表得到index、sheet。 然后使用strings.EqualFold使得sheer和剪枝之后的name忽略大小写进行比较,如果相等,就返回index,否则返回-1。 下面是trimSheetName的源代码。

// trimSheetName provides a function to trim invalid characters by given worksheet
// name.
func trimSheetName(name string) string {
	if strings.ContainsAny(name, ":\\/?*[]") || utf8.RuneCountInString(name) > 31 {
		r := make([]rune, 0, 31)
		for _, v := range name {
			switch v {
			case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
				continue
			default:
				r = append(r, v)
			}
			if len(r) == 31 {
				break
			}
		}
		name = string(r)
	}
	return name
}

其会剪掉:\/?*[]这些不会出现在工作表名的字符。

四、GetSheetMap()

func (f *File) GetSheetMap() map[int]string

获取工作簿中以 ID 和名称构成的全部工作表、图表工作表和对话工作表映射表。 下面是一个使用案例。

f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
    return
}
for index, name := range f.GetSheetMap() {
    fmt.Println(index, name)
}

下面直接上源代码:

func (f *File) GetSheetMap() map[int]string {
	wb := f.workbookReader()
	sheetMap := map[int]string{}
	if wb != nil {
		for _, sheet := range wb.Sheets.Sheet {
			sheetMap[sheet.SheetID] = sheet.Name
		}
	}
	return sheetMap
}

其会读取工作簿,然后将遍历工作簿中的所有工作表,将工作表对象sheet的ID为键,Name为值放入sheetMap中,最后返回sheetMap即可。

总结

这里是Go-Excelize API源码阅读第二十五篇,主要介绍了GetSheetName、GetSheetIndex、GetSheetMap三个API,如果大家喜欢这个系列,大家可以关注我的博客,或者私信博主,与博主一起学习Excelize。