Successfully reported this slideshow.
Your SlideShare is downloading. ×

Go 夜读 139 期 Excelize 基础库

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 30 Ad

More Related Content

Similar to Go 夜读 139 期 Excelize 基础库 (20)

Recently uploaded (20)

Advertisement

Go 夜读 139 期 Excelize 基础库

  1. 1. Go 语言 Excelize 开源基础库介绍 续日 https://github.com/xuri/excelize Go 夜读 第 139 期 Nov. 3, 2022
  2. 2. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 个人介绍 2 续日,软件工程师,阿里巴巴技术专家。 曾就职于百度、360 等公司,前百度 Go 语言编程委员会成员, 从事百度 Go 语言研发体系的建设工作。 开源爱好者,Excelize、aurora、xgen 等开源软件作者 GitHub: @xuri Blog: https://xuri.me
  3. 3. 主要内容 3 Excelize 是 Go 语言编写的用于操作 Office Excel 文档基础库,基于 ECMA-376,ISO/IEC 29500 国际标准。可以使用它来读取、写入由 Microsoft Excel™ 2007 及以上版本创建的电子表格文档。支持 XLSX / XLSM / XLTM 等多种文档格式,高度兼容带有样式、图片(表)、透 视表、切片器等复杂组件的文档,并提供流式读写 API,用于处理包 含大规模数据的工作簿。可应用于各类报表平台、云计算、边缘计算 等系统。入选 2020 Gopher China - Go 领域明星开源项目 (GSP)、 2018 年开源中国码云最有价值开源项目 (Gitee Most Valuable Project) GitHub: https://github.com/xuri/excelize 1. 开发背景 2. 应用价值 3. 快速上手 4. 技术原理 5. 标准解读 6. 部分模块设计与实现 7. 开源现状 8. 未来规划
  4. 4. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 The Spreadsheet Unbundling 4 Create by Foundation Marketing FoundationInc.co
  5. 5. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 开发背景 5  电子表格办公文档有着广泛的应用  自动化电子表格文档处理系统与云计算、边缘计算场景融合  开发者需要通过编程方式处理 Excel 文档  对复杂或包含大规模数据的 Excel 文档进行操作的需求  文档格式领域难以完全实现的复杂技术标准  开源领域、Go 语言缺少具备良好兼容性的基础库
  6. 6. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 应用价值 6 以 Excel 为代表的电子表格文档被广泛应用于教育、医疗、金融等各行各业 商业价值 已经被广泛应用于大型互联网公司、中小企业客户和初创公司,已知超过 20 余家海内外大型企 业,覆盖互联网安全、电子商务、广告、本地生活、金融、自媒体、智能制造等行业 学术价值 数据科学研究过程中,大量通过电子表格文档进行数据分析,Excelize 为这项工作提供多重数据 源之间的数据链接和自动化处理 公益价值 已在全民健身公共服务、新冠疫情防控等涉及社会公共利益相关事业中得到了应用
  7. 7. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 快速上手 (1) 数据读写 7 f := excelize.NewFile() // 创建一个工作表 index := f.NewSheet("Sheet2") // 设置单元格的值 f.SetCellValue("Sheet2", "A2", "Hello world.") f.SetCellValue("Sheet1", "B2", 100) // 获取工作表中指定单元格的值 cell, err := f.GetCellValue("Sheet1", "B2") if err != nil { fmt.Println(err) return } fmt.Println(cell) // 设置工作簿的默认工作表 f.SetActiveSheet(index) // 根据指定路径保存文件 if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } 创建工作簿、设置单元格的值: f, err := excelize.OpenFile("Book1.xlsx") if err != nil { fmt.Println(err) return } defer func() { // 关闭工作簿 if err := f.Close(); err != nil { fmt.Println(err) } }() rows, err := f.GetRows("Sheet1") if err != nil { fmt.Println(err) } for _, row := range rows { for _, colCell := range row { fmt.Print(colCell, "t") } } 打开工作簿、读取工作表中的单元格:
  8. 8. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 快速上手 (2) 数据透视分析 8 借助 Excelize 创建数据透视表按月对各区域在售的商品销售额进行 分类汇总,并支持按销售区域、时间和分类进行筛选 f.AddPivotTable(&excelize.PivotTableOption{ DataRange: "Sheet1!$A$1:$E$31", PivotTableRange: "Sheet1!$G$2:$M$24", Rows: []excelize.PivotTableField{ {Data: "Month", DefaultSubtotal: true}, {Data: "Year"}}, Filter: []excelize.PivotTableField{ {Data: "Region"}}, Columns: []excelize.PivotTableField{ {Data: "Type", DefaultSubtotal: true}}, Data: []excelize.PivotTableField{ {Data: "Sales", Name: "销售额汇总", Subtotal: "Sum"}}, RowGrandTotals: true, ColGrandTotals: true, ShowDrill: true, ShowRowHeaders: true, ShowColHeaders: true, ShowLastColumn: true, })
  9. 9. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 快速上手 (3) 数据可视化 9 f, err := excelize.OpenFile("Book1.xlsx") if err != nil { fmt.Println(err) return } f.AddChart("Sheet1", "E1", `{ "type": "col3DClustered", "series": [ { "name": "Sheet1!$A$2", "categories": "Sheet1!$B$1:$D$1", "values": "Sheet1!$B$2:$D$2" }, { "name": "Sheet1!$A$3", "categories": "Sheet1!$B$1:$D$1", "values": "Sheet1!$B$3:$D$3" }, { "name": "Sheet1!$A$4", "categories": "Sheet1!$B$1:$D$1", "values": "Sheet1!$B$4:$D$4" }], "title": { "name": "三维簇状柱形图" } }`) Excelize 支持二维、三维、面积图、条形、圆锥、棱锥、 柱形、堆积柱形、圆环图、折线图、饼图、雷达图、散点图、 曲面图、气泡图等累计 52 种原生图表与组合图表的创建 0 2 4 6 8 Apple Orange Pear 三维簇状柱形图 Small Normal Large
  10. 10. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 技术原理 10  ISO - ISO/IEC 29500-1:2016  PKWARE ZIP File Format Specifications  Extensible Markup Language (XML) 1.0 (Fifth Edition)  W3C XML Schema Definition Language (XSD)  Unicode® Standard  [MS-OFFCRYPTO]: Office Document Cryptography Structure  [MS-LCID]: Windows Language Code Identifier Reference  DCMI Metadata Terms
  11. 11. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 标准解读 (1) 11 SVG SOAP ODF OOXML C# C++/CLI MIME XSLT XHTML DITA 0 200 400 600 800 1000 1200 0 1000 2000 3000 4000 5000 6000 7000 Technical Committee effort (days) Specification length (pages) Specification Speed
  12. 12. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 标准解读 (2) 12 WordprocessingML SpreadsheetML PresentationML CustomML Vocabularies DrawingML Bibliography Metadata Equations VML (legacy) Relationships Content Types Digital Signatures Markup Languages Open Packaging Convention ZIP XML + Unicode Core Technologies
  13. 13. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 标准解读 (4) B C D E Q1 Q2 Revenue 412.52 Over 10589 Elements & Attributes Shared Strings Calc Chain XML Maps Styles Theme Sheets Table Chart Pivot Table Pivot Cache Pivot Records Workbook <c r="D3" s="7" t="s"> <v>0</v> </c> <xf numFmtId="0" fontId="4" fillId="2" borderId="2" xfId="1" applyBorder="1" /> <font> <sz val="11"/> <color theme="0"/> <name val="Calibri"/> <scheme val="minor"/> </font> <fill> <patternFill patternType="solid"> <fgColor theme="4"/> <bgColor theme=”4"/> </patternFill> </fill> <a:theme xmlns:a="http://schemas.openxmlformats.org <a:themeElements> <a:clrScheme name="Office"> <a:dk1> <a:sysClr val="windowText" /> </a:dk1> <a:lt1> <a:sysClr val="window" /> </a:lt1> <a:dk2> <a:srgbClr val="1F497D"/> </a:dk2> <a:lt2> <a:srgbClr val="FAF3E8"/> </a:lt2> <a:accent1> <a:srgbClr val="5C93B4"/> </a:accent1> <cellStyleXfs count="12"> <xf numFmtId="0" fontId="0" fillId="0" borderId="0"/> <xf numFmtId="0" fontId="4" fillId="2" borderId="0" applyBorder="1" applyAlignment="1" applyProtection="1"/> </protection> </xf> <cellStyles count="2"> <cellStyle name="Accent1" xfId="1" builtinId="29"/> Start (build-in) <border> <left style="thick"> <color auto="1"/> </left> <right style="thick"> <color auto="1"/> </right> <top style="thick"> <color auto="1"/> </top> <bottom style="thick"> <color auto="1"/> </bottom> <diagonal/> </border> 13
  14. 14. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (1) 14 Data Validation Crypto Class Unit Converter Table / Auto Filter Pivot Table File Process Unit Data Processor Conditional Format Chart / Picture 2D / 3D Cluster/Stack/Area Bar/Cone/Pie Bubble/Scatter/Line Time System Combo / Props Wordbook / Worksheet Visibility Properities Header / Footer Search Page Layout Row / Column Alternate Content View Properities Data Protection Streaming I/O Cell Data Types Merge Range Hyperlink Formula Cell Style SST Rich Text Comments Style Index Calc Chain / Cache File Format Processor Style Process Unit Runtime Model Model Components Validator Calculate Engine Formula Lexer / Parser Genetaror VBA Script Excelize Technical Architecture Diagram OPC Processor Meta Processor Relations Parser Embeddings Media Markup Language Broder Fonts Freeze Panes Height/Width Color System Number Format
  15. 15. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (2) Document Object Model 15 <?xml version="1.0" encoding="utf-8"?> <Person> <Name>Tom</Name> <Email where="home"> <Addr>tom@example.com</Addr> </Email> </Person> type Person struct { Name string Email struct { Where string `xml:"where,attr"` Addr string } } encoding/xml var p Person if err := xml.Unmarshal([]byte(data), &p); err != nil { fmt.Println(err) } fmt.Printf("%+vn", p) // {Name:Tom Email:{Where:home Addr:tom@example.com}}
  16. 16. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (3) XML Finite State Machine 0 start start tag NAME TEXT equal end tag value value end value COMMENT version blank/enter letter digit < ? ?> --> !-- = " " ' ' > blank / letter > blank 16
  17. 17. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (4) 17 Unmarshal NewDecoder Decoder.unmarshal Decoder.switchToReader unmarshalPath unmarshalAttr unmarshalInterface unmarshalTextInterface Decoder.RawToken Decoder.pushElement Decoder.pushNs encoding/xml marshal.go typeinfo.go xml.go read.go example & test
  18. 18. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (5) Go Language XML Parser 18 type Decoder struct { Strict bool AutoClose []string Entity map[string]string CharsetReader func(charset string, input io.Reader) (io.Reader, error) DefaultSpace string r io.ByteReader t TokenReader buf bytes.Buffer saved *bytes.Buffer stk *stack free *stack needClose bool toClose Name nextToken Token nextByte int ns map[string]string err error line int offset int64 unmarshalDepth int } encoding/xml:xml.go StartElement EndElement CharData Comment ProcInst Directive
  19. 19. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (6) Go Datatypes XML Datatypes string anyType, ENTITY,ID, IDREF, NCName, NMTOKEN, Name, anyURI, duration, language, normalizedString, string, token, xml:lang, xml:space, xml:base,xml:id []string ENTITIES, IDREFS, NMTOKENS, NOTATION xml.Name QName []byte base64Binary, hexBinary, unsignedByte bool boolean byte byte float64 decimal, double, float, int64 int, integer, long, negativeInteger, nonNegativeInteger, nonPositiveInteger, positiveInteger, short uint64 unsignedInt, unsignedLong, unsignedShort time.Time date, dateTime, gDay, gMonth, gMonthDay, gYear, gYearMonth,time anyType anySimpleType all complex types gYearMonth gYear gMonthDay gDay gMonth date time dateTime duration boolean base64Binary hexBinary float double anyURI QName NOTATION decimal string normalizedString integer token long nonNegativeInteger nonPostitveInteger language Name NMTOKEN negativeInteger int unsignedLong positiveInteger NCName NMTOKENS sort unsignedInt ID IDREF ENTITY ENTITIES IDREFS bytes unsignedSort unsignedByte ur types build-in primitive types build-in derived types complex types derived by restriction Derived by list Derived by extension or restriction 19
  20. 20. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (7) Entity, Namespace & Ser/Deserialize Idempotence <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE person[ <!ENTITY name "Tom"> <!ENTITY email "tom@example.com"> ]> <person> <name>&name;</name> <address>&email;</address> </person> <?xml version="1.0" encoding="utf-8"?> <person xmlns="http://example.com/default" xmlns:m="http://example.com/main" xmlns:h="http://example.com/home" xmlns:w="http://example.com/work"> <name>Tom</name> <m:email h:addr="HOME" w:addr="WORK" /> </person> type Person struct { XMLName xml.Name `xml:"http://example.com/default person"` Name string `xml:"name"` Email struct { XMLName xml.Name `xml:"http://example.com/main email"` HomeAddr string `xml:"http://example.com/home addr,attr"` WorkAddr string `xml:"http://example.com/work addr,attr"` } // TAG NOT HERE: `xml:"email"` } Namespace Local Name <person xmlns="http://example.com/default"> <name>Tom</name> <email xmlns="http://example.com/main" xmlns:home="http://example.com/home" home:addr="HOME" xmlns:work="http://example.com/work" work:addr="WORK"></email> </person> 20
  21. 21. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (8) Ser/Deserialize Idempotence encoding/xml:xml.go type Token interface{} type EndElement struct { Name Name } type Name struct { Space, Local string } type Attr struct { Name Name Value string } type StartElement struct { Name Name Attr []Attr } // getRootEleAttr extract root element attributes by // given XML decoder. func getRootEleAttr(d *xml.Decoder) []xml.Attr { tokenIdx := 0 for { token, _ := d.Token() if token == nil { break } switch startElement := token.(type) { case xml.StartElement: tokenIdx++ if tokenIdx == 1 { return startElement.Attr } } } return nil } 21
  22. 22. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (9) <?xml version="1.0"?> <note xmlns:m="http://example.com/main"> <to>Tom</to> <from>Bob</from> <heading>Reminder</heading> <m:body>Don't forget me this weekend!</m:body> </note> <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:m="http://example.com/main"> <xsd:import namespace="http://example.com/main" schemaLocation="shared.xsd"/> <xs:element name="note"> <xs:complexType> <xs:sequence> <xs:element name="to" type="xs:string"/> <xs:element name="from" type="xs:string"/> <xs:element name="heading" type="xs:string"/> <xs:element name="m:body" use="required"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="body" type="xs:string"/> </xs:schema> shared.xsd 22
  23. 23. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (10) <?xml version="1.0"?> <note xmlns:m="http://example.com/main"> <to>Tom</to> <from>Bob</from> <heading>Reminder</heading> <m:body>Don't forget me this weekend!</m:body> </note> type Note struct { XMLName xml.Name `xml:"note"` To string `xml:"to"` From string `xml:"from"` Heading string `xml:"heading"` Body string `xml:"http://example.com/main body"` } 23
  24. 24. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (11) 24 sml.xsd dml-spreadsheetDrawing.xsd dml-diagram.xsd dml-main.xsd dml-picture.xsd dml-lockedCanvas.xsd dml-chart.xsd dml-chartDrawing.xsd shared-commonSimpleTypes.xsd shared-relationshipReference.xsd
  25. 25. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (12) XSD: XML Schema Definition Process is a named component and has two additional properties - name and target namespace is an un-named component cmd parser NSResolver proto generator Language Code Attribute Attribute Group ComplexType Element Enumeration FractionDigits Pattern SimpleType Schema List Length Import Include Group Restriction TotalDigits Union WhiteSpace MaxLength MinLength MinExclusive Attribute Attribute Group FieldName FieldType ComplexType Element Group SimpleType Generator SAX Parser Schema Notation Declaration system identifier public identifier Element Declaration scope value constraint nillable substitution group affiliation substitution group exclusions disallowed substitutions abstract Simple Type Declaration facets final variety AttributeDeclaration scope value constraint Identity-constraintDeclaration identity-constraintcategory selector fields referenced key Complex Type Declaration derivationmethod final abstract prohibitedsubstitutions Model Group Definition AttributeGroup Definition AttributeUse required value constraint Wildcard namespace constraint process contents Particle min occurs max occurs Model Group compositor notation declarations attributedeclarations type definitions element declarations attributegroup definitions model group definitions type definitions identity-constraint definitions content type type definition type definition term content type base type definition base type definition base type definition attribute uses attribute wildcard term term particles model group attribute wildcard type definition attributedefinitions attributeuses https://github.com/xuri/xgen 25
  26. 26. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 部分模块设计与实现 (13) Common Package Parts Package Relationships Core Properties Digital Signatures Specific Format Parts Office Document Part Relationships XML Part XML Part Part Rels Etc… <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <dimension ref="B2"/> <sheetViews> <sheetView tabSelected="1" workbookViewId="0" /> </sheetViews> <sheetFormatPr baseColWidth="10" defaultRowHeight="16" /> <sheetData> <row r="2"> <c r="B2"> <v>123</v> </c> </row> </sheetData> <pageMargins left="0.7" right="0.7" /> </worksheet> A B C 1 2 123 3 4 26
  27. 27. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 开源现状 (1) 性能 27 7.27 28.96 44.93 16.43 144.89 15.00 101.15 14.27 0 40 80 120 160 Excelize 2.6.1 Stream Mode go1.18.1 darwin/amd64 Excelize 2.6.1 go1.18.1 darwin/amd64 tealeg/xlsx 3.2.4@1a18367 go1.18.1 darwin/amd64 unidoc/unioffice v2.2.0@4702ef2 go1.18.1 darwin/amd64 xlsxWriter RELEASE_1.2.8 python 2.7 Apache POI XSSF 4.1.2 Streaming java version 12.0.1 PhpSpreadsheet 1.23.0 @05d08fe PHP 8.1.4 Zend Engine v4.1.4 SheetJS/js-xlsx 0.18.5 NodeJS 18.1.0 Time Cost (s) Less is better 62 5,126 4,746 2,883 1,083 425 3,014 2,120 0 750 1,500 2,250 3,000 3,750 4,500 5,250 6,000 Excelize 2.6.1 Stream Mode go1.18.1 darwin/amd64 Excelize 2.6.1 go1.18.1 darwin/amd64 tealeg/xlsx 3.2.4@1a18367 go1.18.1 darwin/amd64 unidoc/unioffice v2.2.0@4702ef2 go1.18.1 darwin/amd64 xlsxWriter RELEASE_1.2.8 python 2.7 Apache POI XSSF 4.1.2 Streaming java version 12.0.1 PhpSpreadsheet 1.23.0 @05d08fe PHP 8.1.4 Zend Engine v4.1.4 SheetJS/js-xlsx 0.18.5 NodeJS 18.1.0 Memory Usage (MB) Less is better The following graph shows performance comparison of generation 102400*50 plain text matrix by the major open source Excel libs under personal computer (2.6 GHz 6-Core Intel Core i7, 16 GB 2667 MHz DDR4, 500GB SSD, macOS Monterey 12.3.1), including Go, Python, Java, PHP and NodeJS. Benchmark script: https://github.com/xuri/excelize-benchmark Excelize benchmark report: https://xuri.me/excelize/zh-hans/performance.html
  28. 28. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 开源现状 (2) 28 0 2000 4000 6000 8000 10000 12000 14000 2016 2017 2018 2019 2020 2021 2022 Excelize GitHub Star History Excelize Global Contributors * 截至 2022 年 11 月,GitHub Star 1.3 万,有超过 50 个国家和地区的 350 多名贡献者,其中有 140 余人参与了代码贡献
  29. 29. 续日 · Go 夜读 · Go 语言 Excelize 开源基础库介绍 · 2022.11.03 未来规划 & 发展潜力 29  更多接口将提供并发安全支持  对包含大规模数据文档读写性能的持续优化  公式计算引擎增加更多计算函数  复杂条件格式的设置、数据预测支持  灵活控制图表样式  数据透视表、数据透视图、切片器功能  更加精准的数字格式表达式解析  提供更多可用流式读写接口  跨语言支持  持续活跃的开源技术社区  Go 语言的迅猛发展  跨语言支持进一步拓展开发者生态  企业信息化、数字化与在线办公产业的发展 Excelize 技术交流群
  30. 30. 讨论 Q&A 30

×