• 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
    
    • 1

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

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

    例如:

    err := f.SetAppProps(&excelize.AppProperties{
        Application:       "Microsoft Excel",
        ScaleCrop:         true,
        DocSecurity:       3,
        Company:           "Company Name",
        LinksUpToDate:     true,
        HyperlinksChanged: true,
        AppVersion:        "16.0000",
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

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

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

    来看第一部分:

    	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
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    先使用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
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5

    然后读取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)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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

    fields = []string{"Application", "ScaleCrop", "DocSecurity", "Company", "LinksUpToDate", "HyperlinksChanged", "AppVersion"}
    
    • 1

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

    	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())
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    	app.Vt = NameSpaceDocumentPropertiesVariantTypes.Value
    	output, err = xml.Marshal(app)
    	f.saveFileList(defaultXMLPathDocPropsApp, output)
    
    • 1
    • 2
    • 3

    然后再将

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

    的值赋给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...))
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

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

    三、结语

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

  • 相关阅读:
    阿里云武林头条活动分享
    报告解读下载 | 11月《中国数据库行业分析报告》发布,精彩抢先看
    如何制作有专业水准的的电子杂志:专家教你秘籍
    Jmeter 使用正则表达式提取器将返回值全部保存到一个文件中
    metaRTC达到商用要求的第一个稳定版发布了
    ceph浅谈
    版本号正则校验及大小比较
    无涯教程-JavaScript - ISPMT函数
    STM32连接WIFI-ESP8266实战—AP模式运用
    VSCODE include错误 找不到 stdio.h
  • 原文地址:https://blog.csdn.net/qq_36045898/article/details/126491543