package module
v1.1.6 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Aug 14, 2019 License: MIT Imports: 15 Imported by: 6



Build Status Code Coverage Go Report Card GoDoc License Donate


Helper library to read OOXML documents. Used by other libraries (E.g.: http://github.com/plandem/xlsx).





View Source
const (
	ContentTypeVmlDrawing    ml.ContentType = "application/vnd.openxmlformats-officedocument.vmlDrawing"
	ContentTypeRelationships ml.ContentType = "application/vnd.openxmlformats-package.relationships+xml"

List of all supported ContentType for any office file - excel, word, powerpoint


This section is empty.


func CopyZipFile

func CopyZipFile(from *zip.File, to *zip.Writer) error

CopyZipFile copies a zip file as is to a new zip

func ErrorUnknownPackage

func ErrorUnknownPackage(p interface{}) error

ErrorUnknownPackage returns a common error if DocumentFactoryFn returned invalid result

func GetLettersFn

func GetLettersFn(rune rune) rune

GetLettersFn is a strings.Map walker to return [a-zA-Z] runes from string

func GetNumbersFn

func GetNumbersFn(rune rune) rune

GetNumbersFn is a strings.Map walker to return [0-9] runes from string

func IsEmptyValue

func IsEmptyValue(v reflect.Value) bool

IsEmptyValue returns true if reflected value is 'empty'

func MarshalZipFile

func MarshalZipFile(fileName string, source interface{}, to *zip.Writer) error

MarshalZipFile add a file with content of marshaled source to zip

func Open

func Open(f interface{}, docFactory DocumentFactoryFn) (interface{}, error)

Open opens a file with fileName or io.Reader and returns an instance of document

func UniqueName

func UniqueName(name string, names []string, nameLimit int) string

UniqueName returns next valid unique name with a valid length

func UnmarshalZipFile

func UnmarshalZipFile(f *zip.File, target interface{}) error

UnmarshalZipFile unpacks a zip file into target object


type ContentTypes

type ContentTypes struct {
	// contains filtered or unexported fields

ContentTypes is helper object that implements some functionality for content types that is a required part of any OOXML document

func (*ContentTypes) CountTypes

func (ct *ContentTypes) CountTypes(contentType ml.ContentType) int

CountTypes returns total number of contentType items

func (*ContentTypes) RegisterContent

func (ct *ContentTypes) RegisterContent(fileName string, contentType ml.ContentType)

RegisterContent adds information about a new content with fileName of contentType

func (*ContentTypes) RegisterType

func (ct *ContentTypes) RegisterType(extension string, contentType ml.ContentType)

RegisterType adds information about a new type of content if there is no such type already

func (*ContentTypes) RemoveContent

func (ct *ContentTypes) RemoveContent(fileName string)

RemoveContent removes information about a content with fileName

type DocumentFactoryFn

type DocumentFactoryFn func(pkg *PackageInfo) (interface{}, error)

DocumentFactoryFn is factory to in a OOXML type specific type

type DocumentValidatorFn

type DocumentValidatorFn func() error

DocumentValidatorFn is callback to validate OOXML document. Using right before saving

type MarshalFixation

type MarshalFixation interface {
	AfterMarshalXML(content []byte) []byte

MarshalFixation is interface that must be implemented by complex data if it requires some after marshal fixation

type MarshalPreparation

type MarshalPreparation interface {
	BeforeMarshalXML() interface{}

MarshalPreparation is interface that must be implemented by complex data if it requires some preparation steps before marshaling

type Package

type Package interface {
	Save() error
	SaveAs(target interface{}) error

Package is interface to expose some of PackageInfo methods via embedded struct

type PackageFile

type PackageFile struct {
	// contains filtered or unexported fields

PackageFile is helper object that implements common functionality for any file of package. E.g. lazy loading, marking as updated.

func NewPackageFile

func NewPackageFile(pkg *PackageInfo, f interface{}, target interface{}, source interface{}) *PackageFile

NewPackageFile creates and returns package file that attached target via file f with source of information to save

func (*PackageFile) FileName

func (pf *PackageFile) FileName() string

FileName returns name of file

func (*PackageFile) IsNew

func (pf *PackageFile) IsNew() bool

IsNew returns true if this file is a new file or false in other case

func (*PackageFile) LoadIfRequired

func (pf *PackageFile) LoadIfRequired(callback func())

LoadIfRequired lazy loads whole content of file into target and call required callback if there is any

func (*PackageFile) MarkAsUpdated

func (pf *PackageFile) MarkAsUpdated()

MarkAsUpdated marks file as updated, so content will be replaced with source's content during packing document. Works only with new files or files that where fully loaded (via LoadIfRequired).

func (*PackageFile) ReadStream

func (pf *PackageFile) ReadStream() (*StreamFileReader, error)

ReadStream opens a zip file for manual reading as stream and return *StreamFileReader for it Files that were opened as stream can't be marked as updated via MarkAsUpdated and will be saved as is Files that were opened as stream must be manually closed via calling Close() to prevent memory leaks

func (*PackageFile) WriteStream

func (pf *PackageFile) WriteStream(memory bool, finalizer StreamFileWriterFinalizer) (*StreamFileWriter, error)

WriteStream creates a zip file for manual writing as stream and return StreamFileWriter for it File can be created as stream only once, any further requests will return previously created stream

type PackageInfo

type PackageInfo struct {
	Validator DocumentValidatorFn
	// contains filtered or unexported fields

PackageInfo holds all required information for OOXML package

func NewPackage

func NewPackage(reader interface{}) *PackageInfo

NewPackage returns a new package with zip reader if there is any

func (*PackageInfo) Add

func (pkg *PackageInfo) Add(fileName string, content interface{})

Add is a private method that adds a file to a package

func (*PackageInfo) Close

func (pkg *PackageInfo) Close() error

Close closes current OOXML package

func (*PackageInfo) ContentTypes

func (pkg *PackageInfo) ContentTypes() *ContentTypes

ContentTypes is a getter that returns content types of package

func (*PackageInfo) File

func (pkg *PackageInfo) File(fileName string) interface{}

File is a private method that returns file with required name

func (*PackageInfo) FileName

func (pkg *PackageInfo) FileName() string

FileName is a private method that returns filename of opened file

func (*PackageInfo) Files

func (pkg *PackageInfo) Files(pattern *regexp.Regexp) map[string]interface{}

Files is a private method to get list of all files inside of package, using regexp pattern if required

func (*PackageInfo) IsNew

func (pkg *PackageInfo) IsNew() bool

IsNew returns true if package is a new one or false in other case

func (*PackageInfo) Relationships

func (pkg *PackageInfo) Relationships() *Relationships

Relationships is a getter that returns top-level relationships of package

func (*PackageInfo) Remove

func (pkg *PackageInfo) Remove(fileName string)

Remove is a private method that removes file from a package

func (*PackageInfo) Save

func (pkg *PackageInfo) Save() error

Save saves current OOXML package

func (*PackageInfo) SaveAs

func (pkg *PackageInfo) SaveAs(target interface{}) error

SaveAs saves current OOXML package with fileName or io.Writer

func (*PackageInfo) SavePackage

func (pkg *PackageInfo) SavePackage(f io.Writer) error

SavePackage is private method with implementation of saving OOXML document to file

type Relationships

type Relationships struct {
	// contains filtered or unexported fields

Relationships is a higher level object that wraps OOXML relationships with functionality

func NewRelationships

func NewRelationships(f interface{}, pkg *PackageInfo) *Relationships

NewRelationships creates and returns relationships

func (*Relationships) AddFile

func (rels *Relationships) AddFile(t ml.RelationType, target string) (int, ml.RID)

AddFile adds a new relation of type t to internal target, i.e. file inside of package. For simplicity - use absolute paths.

func (rels *Relationships) AddLink(t ml.RelationType, target string) (int, ml.RID)

AddLink adds a new relation of type t to external target - e.g.: url

func (*Relationships) FileName

func (rels *Relationships) FileName() string

FileName returns file name of relations

func (*Relationships) GetIdByTarget

func (rels *Relationships) GetIdByTarget(target string) ml.RID

GetIdByTarget returns id of first relation for provided target

func (*Relationships) GetTargetById

func (rels *Relationships) GetTargetById(id string) string

GetTargetById returns target of relation for provided id

func (*Relationships) GetTargetByType

func (rels *Relationships) GetTargetByType(t ml.RelationType) string

GetTargetByType returns target of first relation for provided type

func (*Relationships) Remove

func (rels *Relationships) Remove(rid ml.RID)

Remove removes relation with provided rid

func (*Relationships) Total

func (rels *Relationships) Total() int

Total returns total number of relationships

type StreamFileReader

type StreamFileReader struct {
	// contains filtered or unexported fields

StreamFileReader is stream reader for *zip.File

package main

import (

func main() {
	type Cell struct {
		Formula   *ml.Reserved     `xml:"f,omitempty"`
		Value     string           `xml:"v,omitempty"`
		InlineStr *ml.Reserved     `xml:"is,omitempty"`
		ExtLst    *ml.Reserved     `xml:"extLst,omitempty"`
		Ref       string           `xml:"r,attr"`
		Style     int              `xml:"s,attr,omitempty"`
		Type      string           `xml:"t,attr,omitempty"`
		Cm        ml.OptionalIndex `xml:"cm,attr,omitempty"`
		Vm        ml.OptionalIndex `xml:"vm,attr,omitempty"`
		Ph        bool             `xml:"ph,attr,omitempty"`

	type Row struct {
		Cells        []*Cell      `xml:"c"`
		ExtLst       *ml.Reserved `xml:"extLst,omitempty"`
		Ref          int          `xml:"r,attr,omitempty"`
		Spans        string       `xml:"spans,attr,omitempty"`
		Style        int          `xml:"s,attr,omitempty"`
		CustomFormat bool         `xml:"customFormat,attr,omitempty"`
		Height       float32      `xml:"ht,attr,omitempty"`
		Hidden       bool         `xml:"hidden,attr,omitempty"`
		CustomHeight bool         `xml:"customHeight,attr,omitempty"`
		OutlineLevel uint8        `xml:"outlineLevel,attr,omitempty"`
		Collapsed    bool         `xml:"collapsed,attr,omitempty"`
		ThickTop     bool         `xml:"thickTop,attr,omitempty"`
		ThickBot     bool         `xml:"thickBot,attr,omitempty"`
		Phonetic     bool         `xml:"ph,attr,omitempty"`

	openSheet := func(cb func(f *zip.File)) {
		z, err := zip.OpenReader(`./test_files/example_simple.xlsx`)
		if err != nil {

		defer z.Close()

		for _, f := range z.File {
			if f.Name == `xl/worksheets/sheet1.xml` {

	openSheet(func(f *zip.File) {
		stream, _ := ooxml.NewStreamFileReader(f)

		for {
			t, _ := stream.Token()
			if t == nil {

			switch start := t.(type) {
			case xml.StartElement:
				if start.Name.Local == "row" {
					var row Row
					if stream.DecodeElement(&row, &start) == nil {
						for _, c := range row.Cells {
							if c.Type == "s" || c.Value == "" {

							fmt.Printf("%+v\n", c.Value)

		_ = stream.Close()



func NewStreamFileReader

func NewStreamFileReader(f *zip.File) (*StreamFileReader, error)

NewStreamFileReader returns a StreamFileReader for *zip.File f

func (*StreamFileReader) Close

func (s *StreamFileReader) Close() error

Close closes previously opened file for reading

type StreamFileWriter

type StreamFileWriter struct {
	// contains filtered or unexported fields

StreamFileWriter is stream writer for *zip.File

func NewStreamFileWriter

func NewStreamFileWriter(f string, memory bool, finalizer StreamFileWriterFinalizer) (*StreamFileWriter, error)

NewStreamFileWriter returns a StreamFileWriter for fileName

func (*StreamFileWriter) Close added in v1.1.0

func (s *StreamFileWriter) Close() error

Close previously allocated resources for writing

func (*StreamFileWriter) Save

func (s *StreamFileWriter) Save(to *zip.Writer) error

Save current state of stream to *zip.Writer

type StreamFileWriterFinalizer added in v1.1.1

type StreamFileWriterFinalizer func() error

StreamFileWriterFinalizer is callback that will be called to do final processing before closing stream


Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL