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

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)

func (f *File) SetAppProps(appProperties *AppProperties) error

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

//     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 代表数值,否则文件将不符合标准

例如:

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

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

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
}

来看第一部分:

	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。

	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 类似,不同之处在于它读取解码器流来查找开始元素。 下面是它们的源码:

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)
}

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

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)

然后再将

NameSpaceDocumentPropertiesVariantTypes = xml.Attr{Name: xml.Name{Local: "vt", Space: "xmlns"}, Value: "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"}

的值赋给app.Vt。

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

// 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语言相关源码的解读第二十二篇,我会不断努力,给大家带来更多类似的文章,恳请大家不吝赐教。

原文地址:https://cloud.tencent.com/developer/article/2119979

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习编程?其实不难,不过在学习编程之前你得先了解你的目的是什么?这个很重要,因为目的决定你的发展方向、决定你的发展速度。
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面设计类、前端与移动、开发与测试、营销推广类、数据运营类、运营维护类、游戏相关类等,根据不同的分类下面有细分了不同的岗位。
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生学习Java开发,但要结合自身的情况,先了解自己适不适合去学习Java,不要盲目的选择不适合自己的Java培训班进行学习。只要肯下功夫钻研,多看、多想、多练
Can’t connect to local MySQL server through socket \'/var/lib/mysql/mysql.sock问题 1.进入mysql路径
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 sqlplus / as sysdba 2.普通用户登录
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服务器有时候会断掉,所以写个shell脚本每五分钟去判断是否连接,于是就有下面的shell脚本。
BETWEEN 操作符选取介于两个值之间的数据范围内的值。这些值可以是数值、文本或者日期。
假如你已经使用过苹果开发者中心上架app,你肯定知道在苹果开发者中心的web界面,无法直接提交ipa文件,而是需要使用第三方工具,将ipa文件上传到构建版本,开...
下面的 SQL 语句指定了两个别名,一个是 name 列的别名,一个是 country 列的别名。**提示:**如果列名称包含空格,要求使用双引号或方括号:
在使用H5混合开发的app打包后,需要将ipa文件上传到appstore进行发布,就需要去苹果开发者中心进行发布。​
+----+--------------+---------------------------+-------+---------+
数组的声明并不是声明一个个单独的变量,比如 number0、number1、...、number99,而是声明一个数组变量,比如 numbers,然后使用 nu...
第一步:到appuploader官网下载辅助工具和iCloud驱动,使用前面创建的AppID登录。
如需删除表中的列,请使用下面的语法(请注意,某些数据库系统不允许这种在数据库表中删除列的方式):
前不久在制作win11pe,制作了一版,1.26GB,太大了,不满意,想再裁剪下,发现这次dism mount正常,commit或discard巨慢,以前都很快...
赛门铁克各个版本概览:https://knowledge.broadcom.com/external/article?legacyId=tech163829
实测Python 3.6.6用pip 21.3.1,再高就报错了,Python 3.10.7用pip 22.3.1是可以的
Broadcom Corporation (博通公司,股票代号AVGO)是全球领先的有线和无线通信半导体公司。其产品实现向家庭、 办公室和移动环境以及在这些环境...
发现个问题,server2016上安装了c4d这些版本,低版本的正常显示窗格,但红色圈出的高版本c4d打开后不显示窗格,
TAT:https://cloud.tencent.com/document/product/1340