Go-Excelize API 源码阅读(十一)—— GetActiveSheetIndex()
一、Go-Excelize 简介
Excelize 是 Go 语言编写的用于操作 Office Excel 文档基础库,基于 ECMA-376,ISO/IEC 29500 国际标准。可以使用它来读取、写入由 Microsoft Excel™ 2007 及以上版本创建的电子表格文档。支持 XLAM / XLSM / XLSX / XLTM / XLTX 等多种文档格式,高度兼容带有样式、图片(表)、透视表、切片器等复杂组件的文档,并提供流式读写 API,用于处理包含大规模数据的工作簿。可应用于各类报表平台、云计算、边缘计算等系统。使用本类库要求使用的 Go 语言为 1.15 或更高版本。
二、GetActiveSheetIndex()
func (f *File) GetActiveSheetIndex() int
复制代码
该 API 的作用是获取默认工作表的索引,如果没有找到默认工作表将返回 0。
废话少说,直接上源码:
// GetActiveSheetIndex provides a function to get active sheet index of the// spreadsheet. If not found the active sheet will be return integer 0.func (f *File) GetActiveSheetIndex() (index int) { sheetID := f.getActiveSheetID() wb := f.workbookReader() if wb != nil { for idx, sheet := range wb.Sheets.Sheet { if sheet.SheetID == sheetID { index = idx return } } } return}
复制代码
看到这个sheetID := f.getActiveSheetID()
getActiveSheetID 提供了一个函数来获取电子表格的活动工作表 ID。如果未找到活动工作表,将返回整数 0。
func (f *File) getActiveSheetID() int { wb := f.workbookReader() if wb != nil { if wb.BookViews != nil && len(wb.BookViews.WorkBookView) > 0 { activeTab := wb.BookViews.WorkBookView[0].ActiveTab if len(wb.Sheets.Sheet) > activeTab && wb.Sheets.Sheet[activeTab].SheetID != 0 { return wb.Sheets.Sheet[activeTab].SheetID } } if len(wb.Sheets.Sheet) >= 1 { return wb.Sheets.Sheet[0].SheetID } } return 0}
复制代码
其实就是读取表格文件,然后获取工作簿视图队列第一个 ActiveTab。ActiveTab 我在微软文档没有找到,我猜测是活动视图队列的工作表序号。
type xlsxWorkBookView struct { Visibility string `xml:"visibility,attr,omitempty"` Minimized bool `xml:"minimized,attr,omitempty"` ShowHorizontalScroll *bool `xml:"showHorizontalScroll,attr"` ShowVerticalScroll *bool `xml:"showVerticalScroll,attr"` ShowSheetTabs *bool `xml:"showSheetTabs,attr"` XWindow string `xml:"xWindow,attr,omitempty"` YWindow string `xml:"yWindow,attr,omitempty"` WindowWidth int `xml:"windowWidth,attr,omitempty"` WindowHeight int `xml:"windowHeight,attr,omitempty"` TabRatio int `xml:"tabRatio,attr,omitempty"` FirstSheet int `xml:"firstSheet,attr,omitempty"` ActiveTab int `xml:"activeTab,attr,omitempty"` AutoFilterDateGrouping *bool `xml:"autoFilterDateGrouping,attr"`}
复制代码
if len(wb.Sheets.Sheet) > activeTab && wb.Sheets.Sheet[activeTab].SheetID != 0 { return wb.Sheets.Sheet[activeTab].SheetID }
复制代码
活动视图队列第一个工作表序号不能大于工作表的数量,并且其工作表 ID 不等于 0。如此,便可以返回活动视图队列第一个工作表的工作表 ID。
if len(wb.Sheets.Sheet) >= 1 { return wb.Sheets.Sheet[0].SheetID }
复制代码
如果工作簿视图不存在,或者工作簿视图数量等于 0,并且工作表的数量大于等于 1,那么就返回索引为 0 的工作表的 ID。
wb := f.workbookReader() if wb != nil { for idx, sheet := range wb.Sheets.Sheet { if sheet.SheetID == sheetID { index = idx return } } }
复制代码
读取工作簿,然后如果工作簿为空,就会导致sheetID := f.getActiveSheetID()获取的工作表 ID 为 0,所以会返回 0。
如果不为空,就遍历工作表,当工作表 ID 为 getActiveSheetID()获取到的活跃工作表 ID 时,取其工作表索引,返回。
三、结语
这里是老岳,这是 Go 语言相关源码的解读第十一篇,我会不断努力,给大家带来更多类似的文章,恳请大家不吝赐教。
评论