excel

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2023 License: MIT Imports: 7 Imported by: 0

README

excel

Marshal and Unmarshal Excel file with the help of excelize.

Installation

go get github.com/go-mods/excel

Usage

Consider the following structs

type Employee struct {
    // use field name as default column name
    ID int
    // map the column 'firstName'
    First string `excel:"firstName,default:anonymous"`
    // column can also be used to set the column name
    FirstPtr *string `excel:"column:firstName,export:false" excel-out:"-"`
    // map the column 'lastName'
    Last string `excel:"lastName,default:anonymous"`
    // 'column' can be omitted when only mapping to column name
    // this is equal to 'column(email)'
    Email string `excel:"email"`
    // map the column 'contactNumber'
    ContactNumber string `excel:"contactNumber"`
    // map the column 'age'
    Age int `excel:"age"`
    // map the column 'dob'
    BirthDate time.Time `excel:"dob,format:d/m/Y,default:"`
    // map the column 'salary'
    Salary int `excel:"salary"`
    // Slice of staff ID's
    // split will split the string into slice using `|` separator
    Staff []int `excel:"staff,split:|" excel-out:"split:;"`
    // Slice of pointer of staff ID's
    StaffPtr []*int `excel:"staff,split:|,export:false" excel-out:"-"`
    // 'FullName' column contains a json string
    EncodedName EncodedName `excel:"encodedName,encoding:json"`
    // 'FullName' column contains a json string
    EncodedNamePtr *EncodedName `excel:"encodedName,encoding:json,export:false" excel-out:"-"`
    // use '-' to ignore.
    Ignored string `excel:"-"`
}

type EncodedName struct {
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	FullName  string `json:"full_name"`
}
Unmarshal Excel file to struct
package main

import (
	"github.com/go-mods/excel"
	"github.com/xuri/excelize/v2"
)

func main() {
    // Open the employees test file
    file, _ := excelize.OpenFile(employeesTestFile)
    defer func() { _ = file.Close() }()
    
    // Employees container
    var employees []*Employee

    // Configure what to read in the Excel file
    excel, _ := excel.NewReader(file)
    excel.SetSheetName(employeesSheet)
    excel.SetAxis(employeesAxis)

	// Unmarshal employees
    err := excel.Unmarshal(&employees)
    if err != nil {
        t.Error(err)
        return
    }
}
Marshal Excel file from struct
package main

import (
	"github.com/go-mods/excel"
	"github.com/xuri/excelize/v2"
)

func main() {
    // Create a new Excel file
    file := excelize.NewFile()
    file.SetSheetName(file.GetSheetName(file.GetActiveSheetIndex()), employeesSheet)
    defer func() { _ = file.Close() }()

    // Employees container
    var employees []*Employee
    employee1 := &Employee{ID: 1, First: "First", Last: "last", Email: "test@test.com", BirthDate: time.Now()}
    employee2 := &Employee{ID: 2, First: "Second", Last: "last", Salary: 100, EncodedName: EncodedName{FirstName: "Second", LastName: "last", FullName: "Second last"}}
    employee3 := &Employee{ID: 3, BirthDate: time.Now(), Age: 32, Staff: []int{1, 2}}
    employees = append(employees, employee1, employee2, employee3)

    // Configure how to write in the Excel file
    excel, _ := excel.NewWriter(file)
    excel.SetSheetName(employeesSheet)
    excel.SetAxis(employeesAxis)
    
    // Unmarshal employees
    err := excel.Marshal(&employees)
        if err != nil {
        t.Error(err)
        return
    }
    
    // Save file
    _ = file.SaveAs(employeesExportFile)
}

Customizable Converters

type DateTime struct {
    time.Time
}

func (date *DateTime) Marshall() (interface{}, error) {
    return date.Time.Format("20060201"), nil
}

func (date *DateTime) Unmarshall(s string) (err error) {
    date.Time, err = time.Parse("20060201", s)
    return err
}

type User struct {
    Id       int       `excel:"Id"`
    Name     string    `excel:"Name"`
    Created  DateTime  `excel:"Created"`
    Modified *DateTime `excel:"Modified"`
}

Tags

This is the list of tags that can be used. excel-in and excel-out always have precedence on excel

Tags description excel excel-in excel-out
column Field name in the title row.
by default the field name will be used
in and out can be differents
X X X
default Default value to use when none is defined in the cell. X X
format Format to apply X X X
encoding Encode or decode to the specified format
only json encoding is supported at the moment
X X X
split Define the split separator to use for array or slice field. X X X
required Will return ann error if the column is not present X X
- Do not map the field to a column X X X

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrFileIsNil      = errors.New("excel: the file is nil")
	ErrSheetNotValid  = errors.New("excel: the sheet name is not valid")
	ErrAxisNotValid   = errors.New("excel: the axis is not valid")
	ErrConfigNotValid = errors.New("excel: the configuration is not valid")

	ErrNoReaderFound = errors.New("excel: unable to create an appropriate reader")
	ErrNoWriterFound = errors.New("excel: unable to create an appropriate writer")

	ErrContainerInvalid = errors.New("excel: the ContainerInfo must be a slice or a pointer")
	ErrColumnRequired   = errors.New("excel: required colum")

	ErrNotImplemented = errors.New("excel: not implemented")
)

Functions

This section is empty.

Types

type Axis

type Axis struct {
	Axis string
	Col  int
	Row  int
}

Axis represent the coordinates in the Excel file where data will read or write

type ContainerInfo

type ContainerInfo struct {
	// contains filtered or unexported fields
}

type Excel

type Excel struct {
	File       *excelize.File
	ReaderInfo *ReaderInfo
	WriterInfo *WriterInfo
}

func NewReader

func NewReader(file *excelize.File) (*Excel, error)

NewReader create the configuration used by the reader

func NewWriter

func NewWriter(file *excelize.File) (*Excel, error)

NewWriter create the configuration used by the writer

func (*Excel) GetSheetIndex

func (e *Excel) GetSheetIndex() int

func (*Excel) GetSheetName

func (e *Excel) GetSheetName() string

func (*Excel) Marshal

func (e *Excel) Marshal(container any) error

func (*Excel) SetAxis

func (e *Excel) SetAxis(axis string)

func (*Excel) SetAxisCoordinates

func (e *Excel) SetAxisCoordinates(col int, row int)

func (*Excel) SetSheetIndex

func (e *Excel) SetSheetIndex(index int)

func (*Excel) SetSheetName

func (e *Excel) SetSheetName(sheet string)

func (*Excel) Unmarshal

func (e *Excel) Unmarshal(container any) error

func (*Excel) Validate

func (e *Excel) Validate() error

type FieldInfo

type FieldInfo struct {
	FieldIndex int
	FieldType  reflect.Type

	Tags    *FieldTags
	TagsIn  *FieldTags
	TagsOut *FieldTags
}

func (*FieldInfo) ColumnNameIn

func (f *FieldInfo) ColumnNameIn() string

func (*FieldInfo) ColumnNameOut

func (f *FieldInfo) ColumnNameOut() string

func (*FieldInfo) DefaultValueIn

func (f *FieldInfo) DefaultValueIn() interface{}

func (*FieldInfo) DefaultValueOut

func (f *FieldInfo) DefaultValueOut() interface{}

func (*FieldInfo) EncodingIn

func (f *FieldInfo) EncodingIn() string

func (*FieldInfo) EncodingOut

func (f *FieldInfo) EncodingOut() string

func (*FieldInfo) FormatIn

func (f *FieldInfo) FormatIn() string

func (*FieldInfo) FormatOut

func (f *FieldInfo) FormatOut() string

func (*FieldInfo) IgnoreIn

func (f *FieldInfo) IgnoreIn() bool

func (*FieldInfo) IgnoreOut

func (f *FieldInfo) IgnoreOut() bool

func (*FieldInfo) IsRequiredIn

func (f *FieldInfo) IsRequiredIn() bool

func (*FieldInfo) IsRequiredOut

func (f *FieldInfo) IsRequiredOut() bool

func (*FieldInfo) SplitIn

func (f *FieldInfo) SplitIn() string

func (*FieldInfo) SplitOut

func (f *FieldInfo) SplitOut() string

type FieldTags

type FieldTags struct {
	ColumnName string

	DefaultValue interface{}
	Format       string
	Encoding     string
	Split        string
	IsRequired   bool
	Ignore       bool
	// contains filtered or unexported fields
}

FieldTags which can be used when reading or writing

type FieldsTags

type FieldsTags interface {
	GetFieldsTags() map[string]*FieldTags
}

The FieldsTags interface can be used as a replacement of the tags parameters.

type FieldsTagsIn

type FieldsTagsIn interface {
	GetFieldsTagsIn() map[string]*FieldTags
}

The FieldsTagsIn interface can be used as a replacement of the tags parameters when importing an Excel file.

type FieldsTagsOut

type FieldsTagsOut interface {
	GetFieldsTagsOut() map[string]*FieldTags
}

The FieldsTagsOut interface can be used as a replacement of the tags parameters when exporting an Excel file.

type Marshaller

type Marshaller interface {
	Marshall() (interface{}, error)
}

Marshaller can be implemented by any value that has a Marshal method This converter is used to convert the value to the desired representation

type Reader

type Reader interface {
	Unmarshall() error
}

Reader interface

type ReaderInfo

type ReaderInfo struct {
	Sheet Sheet
	Axis  Axis
	// contains filtered or unexported fields
}

func (*ReaderInfo) GetSheetIndex

func (r *ReaderInfo) GetSheetIndex() (int, error)

func (*ReaderInfo) GetSheetName

func (r *ReaderInfo) GetSheetName() string

func (*ReaderInfo) SetAxis

func (r *ReaderInfo) SetAxis(axis string)

func (*ReaderInfo) SetAxisCoordinates

func (r *ReaderInfo) SetAxisCoordinates(col int, row int)

func (*ReaderInfo) SetSheetIndex

func (r *ReaderInfo) SetSheetIndex(i int)

func (*ReaderInfo) SetSheetName

func (r *ReaderInfo) SetSheetName(n string)

func (*ReaderInfo) Validate

func (r *ReaderInfo) Validate() error

type Sheet

type Sheet struct {
	Name  string
	Index int
}

Sheet represent the sheet in the Excel file where data will read or write

type StructInfo

type StructInfo struct {
	StructType reflect.Type
	Fields     []*FieldInfo
}

func (*StructInfo) GetFieldFromFieldIndex

func (s *StructInfo) GetFieldFromFieldIndex(index int) *FieldInfo

type Unmarshaller

type Unmarshaller interface {
	Unmarshall(s string) error
}

Unmarshaller can be implemented by any value that has an Unmarshall method This converter is used to convert the value to the desired representation

type Writer

type Writer interface {
	Marshall(data any) error
}

Writer interface

type WriterInfo

type WriterInfo struct {
	Sheet Sheet
	Axis  Axis
	// contains filtered or unexported fields
}

func (*WriterInfo) GetSheetIndex

func (w *WriterInfo) GetSheetIndex() (int, error)

func (*WriterInfo) GetSheetName

func (w *WriterInfo) GetSheetName() string

func (*WriterInfo) SetAxis

func (w *WriterInfo) SetAxis(axis string)

func (*WriterInfo) SetAxisCoordinates

func (w *WriterInfo) SetAxisCoordinates(col int, row int)

func (*WriterInfo) SetSheetIndex

func (w *WriterInfo) SetSheetIndex(i int)

func (*WriterInfo) SetSheetName

func (w *WriterInfo) SetSheetName(n string)

func (*WriterInfo) Validate

func (w *WriterInfo) Validate() error

Jump to

Keyboard shortcuts

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