前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go-Excelize API源码阅读(二十二)——SetAppProps(appProperties *AppProperties)

Go-Excelize API源码阅读(二十二)——SetAppProps(appProperties *AppProperties)

作者头像
Regan Yue
发布2022-09-23 15:41:23
2880
发布2022-09-23 15:41:23
举报
文章被收录于专栏:ReganYue's Blog

Go-Excelize API源码阅读(二十一)——SetAppProps(appProperties *AppProperties)

开源摘星计划(WeOpen Star) 是由腾源会 2022 年推出的全新项目,旨在为开源人提供成长激励,为开源项目提供成长支持,助力开发者更好地了解开源,更快地跨越鸿沟,参与到开源的具体贡献与实践中。

不管你是开源萌新,还是希望更深度参与开源贡献的老兵,跟随“开源摘星计划”开启你的开源之旅,从一篇学习笔记、到一段代码的提交,不断挖掘自己的潜能,最终成长为开源社区的“闪亮之星”。

我们将同你一起,探索更多的可能性!

项目地址: WeOpen-Star:https://github.com/weopenprojects/WeOpen-Star

一、Go-Excelize简介

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

二、 SetAppProps(appProperties *AppProperties)
代码语言:javascript
复制
func (f *File) SetAppProps(appProperties *AppProperties) error

设置工作簿的应用程序属性。可以设置的属性包括:

代码语言:javascript
复制
//     Property          | Description
//    -------------------+--------------------------------------------------------------------------
//     Application       | The name of the application that created this document.
//                       | 创建此文档的应用程序的名称 
//     ScaleCrop         | Indicates the display mode of the document thumbnail. Set this element
//                       | to 'true' to enable scaling of the document thumbnail to the display. Set
//                       | this element to 'false' to enable cropping of the document thumbnail to
//                       | show only sections that will fit the display.
//                       | 指定文档缩略图的显示方式。设置为 true 指定将文档缩略图缩放显示,设置为 false 指定将文档缩略图剪裁显示
//     DocSecurity       | Security level of a document as a numeric value. Document security is
//                       | defined as:以数值表示的文档安全级别。文档安全定义为:
//                       | 1 - Document is password protected.1 - 文档受密码保护
//                       | 2 - Document is recommended to be opened as read-only.2 - 文档受密码保护
//                       | 3 - Document is enforced to be opened as read-only.3 - 强制以只读方式打开文档
//                       | 4 - Document is locked for annotation.4 - 文档批注被锁定
//                       |
//     Company           | The name of a company associated with the document.
//                       | 与文档关联的公司的名称
//     LinksUpToDate     | Indicates whether hyperlinks in a document are up-to-date. Set this
//                       | element to 'true' to indicate that hyperlinks are updated. Set this
//                       | element to 'false' to indicate that hyperlinks are outdated.
//                       | 设置文档中的超链接是否是最新的。设置为 true 表示超链接已更新,设置为 false 表示超链接已过时
//     HyperlinksChanged | Specifies that one or more hyperlinks in this part were updated
//                       | exclusively in this part by a producer. The next producer to open this
//                       | document shall update the hyperlink relationships with the new
//                       | hyperlinks specified in this part.
//                       | 指定下一次打开此文档时是否应使用本部分中指定的新超链接更新超链接关系
//     AppVersion        | Specifies the version of the application which produced this document.
//                       | The content of this element shall be of the form XX.YYYY where X and Y
//                       | represent numerical values, or the document shall be considered
//                       | non-conformant.
//                       | 指定生成此文档的应用程序的版本。值应为 XX.YYYY 格式,其中 X 和 Y 代表数值,否则文件将不符合标准

例如:

代码语言:javascript
复制
err := f.SetAppProps(&excelize.AppProperties{
    Application:       "Microsoft Excel",
    ScaleCrop:         true,
    DocSecurity:       3,
    Company:           "Company Name",
    LinksUpToDate:     true,
    HyperlinksChanged: true,
    AppVersion:        "16.0000",
})

废话少说,我们直接来看一看源码:

代码语言:javascript
复制
func (f *File) SetAppProps(appProperties *AppProperties) (err error) {
	var (
		app                *xlsxProperties
		fields             []string
		output             []byte
		immutable, mutable reflect.Value
		field              string
	)
	app = new(xlsxProperties)
	if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(defaultXMLPathDocPropsApp)))).
		Decode(app); err != nil && err != io.EOF {
		err = fmt.Errorf("xml decode error: %s", err)
		return
	}
	fields = []string{"Application", "ScaleCrop", "DocSecurity", "Company", "LinksUpToDate", "HyperlinksChanged", "AppVersion"}
	immutable, mutable = reflect.ValueOf(*appProperties), reflect.ValueOf(app).Elem()
	for _, field = range fields {
		immutableField := immutable.FieldByName(field)
		switch immutableField.Kind() {
		case reflect.Bool:
			mutable.FieldByName(field).SetBool(immutableField.Bool())
		case reflect.Int:
			mutable.FieldByName(field).SetInt(immutableField.Int())
		default:
			mutable.FieldByName(field).SetString(immutableField.String())
		}
	}
	app.Vt = NameSpaceDocumentPropertiesVariantTypes.Value
	output, err = xml.Marshal(app)
	f.saveFileList(defaultXMLPathDocPropsApp, output)
	return
}

来看第一部分:

代码语言:javascript
复制
	var (
		app                *xlsxProperties
		fields             []string
		output             []byte
		immutable, mutable reflect.Value
		field              string
	)
	app = new(xlsxProperties)
	if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(defaultXMLPathDocPropsApp)))).
		Decode(app); err != nil && err != io.EOF {
		err = fmt.Errorf("xml decode error: %s", err)
		return
	}

先使用var一次定义要使用的所有变量,然后使用new分配一块内存,返回这块内存的地址就赋给了app。

代码语言:javascript
复制
	if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(defaultXMLPathDocPropsApp)))).
		Decode(app); err != nil && err != io.EOF {
		err = fmt.Errorf("xml decode error: %s", err)
		return
	}

然后读取xml文件:defaultXMLPathDocPropsApp

在这里插入图片描述
在这里插入图片描述

Decode 的工作方式与 Unmarshal 类似,不同之处在于它读取解码器流来查找开始元素。 下面是它们的源码:

代码语言:javascript
复制
func Unmarshal(data []byte, v any) error {
	return NewDecoder(bytes.NewReader(data)).Decode(v)
}

func (d *Decoder) Decode(v any) error {
	return d.DecodeElement(v, nil)
}

func (d *Decoder) DecodeElement(v any, start *StartElement) error {
	val := reflect.ValueOf(v)
	if val.Kind() != reflect.Pointer {
		return errors.New("non-pointer passed to Unmarshal")
	}
	return d.unmarshal(val.Elem(), start, 0)
}

接下来建立了一个字段数组:

代码语言:javascript
复制
fields = []string{"Application", "ScaleCrop", "DocSecurity", "Company", "LinksUpToDate", "HyperlinksChanged", "AppVersion"}

然后使用反射将配置文件中的各字段设置相应的数据类型:

代码语言:javascript
复制
	immutable, mutable = reflect.ValueOf(*appProperties), reflect.ValueOf(app).Elem()
	for _, field = range fields {
		immutableField := immutable.FieldByName(field)
		switch immutableField.Kind() {
		case reflect.Bool:
			mutable.FieldByName(field).SetBool(immutableField.Bool())
		case reflect.Int:
			mutable.FieldByName(field).SetInt(immutableField.Int())
		default:
			mutable.FieldByName(field).SetString(immutableField.String())
		}
	}
代码语言:javascript
复制
	app.Vt = NameSpaceDocumentPropertiesVariantTypes.Value
	output, err = xml.Marshal(app)
	f.saveFileList(defaultXMLPathDocPropsApp, output)

然后再将

代码语言:javascript
复制
NameSpaceDocumentPropertiesVariantTypes = xml.Attr{Name: xml.Name{Local: "vt", Space: "xmlns"}, Value: "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"}

的值赋给app.Vt。

再使用xml.Marshal(app),进行xml编码。

代码语言:javascript
复制
// saveFileList provides a function to update given file content in file list
// of spreadsheet.
func (f *File) saveFileList(name string, content []byte) {
	f.Pkg.Store(name, append([]byte(xml.Header), content...))
}

再使用 saveFileList 更新电子表格文件列表中给定文件内容。

三、结语

这里是老岳,这是Go语言相关源码的解读第二十二篇,我会不断努力,给大家带来更多类似的文章,恳请大家不吝赐教。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-08-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Go-Excelize API源码阅读(二十一)——SetAppProps(appProperties *AppProperties)
    • 一、Go-Excelize简介
      • 二、 SetAppProps(appProperties *AppProperties)
        • 三、结语
        相关产品与服务
        边缘可用区
        腾讯云边缘可用区(TencentCloud Edge Zone,TEZ)是腾讯云的本地扩展,适用于解决计算、存储和服务可用性问题。腾讯云边缘可用区可为您带来云的诸多优势,例如弹性、可扩展性和安全性。借助腾讯云边缘可用区,您可以在靠近最终用户的地理位置运行对延迟敏感的应用程序,基本消除延迟问题。腾讯云边缘可用区提供与中心节点一致的体验,助力业务下沉,具备更低延时、更广覆盖、更少成本等特点。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档