Excelize 是 Go 语言编写的用于操作 Office Excel 文档基础库,基于 ECMA-376,ISO/IEC 29500 国际标准。
可以使用它来读取、写入由 Microsoft Excel™ 2007 及以上版本创建的电子表格文档。
支持 XLAM / XLSM / XLSX / XLTM / XLTX 等多种文档格式,高度兼容带有样式、图片(表)、透视表、切片器等复杂组件的文档,并提供流式读写 API,用于处理包含大规模数据的工作簿。
可应用于各类报表平台、云计算、边缘计算等系统。使用本类库要求使用的 Go 语言为 1.15 或更高版本。
1 |
func (f *File) SetSheetViewOptions(sheet string, viewIndex int, opts ...SheetViewOption) error |
根据给定的工作表名称、视图索引和视图参数设置工作表视图属性,viewIndex 可以是负数,如果是这样,则向后计数(-1 代表最后一个视图)。
可选视图参数 | 类型 |
---|---|
DefaultGridColor | bool |
ShowFormulas | bool |
ShowGridLines | bool |
ShowRowColHeaders | bool |
ShowZeros | bool |
RightToLeft | bool |
ShowRuler | bool |
View | string |
TopLeftCell | string |
ZoomScale | float64 |
下面是一个该API的使用例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
f := excelize.NewFile() const sheet = "Sheet1" if err := f.SetSheetViewOptions(sheet, 0, excelize.DefaultGridColor(false), excelize.ShowFormulas(true), excelize.ShowGridLines(true), excelize.ShowRowColHeaders(true), excelize.RightToLeft(false), excelize.ShowRuler(false), excelize.View("pageLayout"), excelize.TopLeftCell("C3"), excelize.ZoomScale(80), ); err != nil { fmt.Println(err) } var zoomScale ZoomScale fmt.Println("Default:") fmt.Println("- zoomScale: 80") if err := f.SetSheetViewOptions(sheet, 0, excelize.ZoomScale(500)); err != nil { fmt.Println(err) } if err := f.GetSheetViewOptions(sheet, 0, &zoomScale); err != nil { fmt.Println(err) } fmt.Println("Used out of range value:") fmt.Println("- zoomScale:", zoomScale) if err := f.SetSheetViewOptions(sheet, 0, excelize.ZoomScale(123)); err != nil { fmt.Println(err) } if err := f.GetSheetViewOptions(sheet, 0, &zoomScale); err != nil { fmt.Println(err) } fmt.Println("Used correct value:") fmt.Println("- zoomScale:", zoomScale) |
其输出结果如下:
Default:
- zoomScale: 80
Used out of range value:
- zoomScale: 80
Used correct value:
- zoomScale: 123
废话少说,直接上源码:
1 2 3 4 5 6 7 8 9 10 |
func (f *File) SetSheetViewOptions(name string, viewIndex int, opts ...SheetViewOption) error { view, err := f.getSheetView(name, viewIndex) if err != nil { return err } for _, opt := range opts { opt.setSheetViewOption(view) } return nil } |
先根据工作表视图的索引取工作表视图。
这个函数其实逻辑很简单,就是判断下标是不是合法的,然后直接返回就是的了,如果默认下标是合法的,那么都不需要这个函数了直接ws.SheetViews.SheetView[viewIndex].
然后再遍历不定长参数opts
1 2 3 |
for _, opt := range opts { opt.setSheetViewOption(view) } |
opt都是SheetViewOption interface类型,其下有一个函数。
此处我们使用的是这个函数....
逻辑都很简单,就是将传来的值处理成工作表视图属性能够设置的值。
然后直接赋值传递过去。
下面介绍一下这些参数的含义: