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

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...