exl

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2023 License: Apache-2.0 Imports: 9 Imported by: 2

README

exl

Excel binding to struct written in Go.(Only supports Go1.18+)

CircleCI GitHub go.mod Go version codecov Go Report Card GoDoc Mentioned in Awesome Go

usage

Read Excel
package main

import (
	"fmt"
	
	"github.com/go-the-way/exl"
)

type ReadExcel struct {
	ID   int    `excel:"ID"`
	Name string `excel:"Name"`
}

func (*ReadExcel) ReadConfigure(rc *exl.ReadConfig) {}

func main() {
	if models, err := exl.ReadFile[*ReadExcel]("/to/path.xlsx"); err != nil {
		fmt.Println("read excel err:" + err.Error())
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
	}
}
Write Excel
package main

import (
	"fmt"
	
	"github.com/go-the-way/exl"
)

type WriteExcel struct {
	ID   int    `excel:"ID"`
	Name string `excel:"Name"`
}

func (m *WriteExcel) WriteConfigure(wc *exl.WriteConfig) {}

func main() {
	if err := exl.Write("/to/path.xlsx", []*WriteExcel{{100, "apple"}, {200, "pear"}}); err != nil {
		fmt.Println("write excel err:" + err.Error())
	} else {
		fmt.Println("write excel done")
	}
}

Writer

package main

import (
	"fmt"

	"github.com/go-the-way/exl"
)

func main() {
	w := exl.NewWriter()
	if err := w.Write("int", []int{1, 2}); err != nil {
		fmt.Println(err)
		return
	}
	if err := w.Write("float", []float64{1.1, 2.2}); err != nil {
		fmt.Println(err)
		return
	}
	if err := w.Write("string", []string{"hello", "world"}); err != nil {
		fmt.Println(err)
		return
	}
	if err := w.Write("map", []map[string]string{{"id":"1000","name":"hello"},{"id":"2000","name":"world"}}); err != nil {
		fmt.Println(err)
		return
	}
	if err := w.Write("structWithField", []struct{ID int}{{1000},{2000}}); err != nil {
		fmt.Println(err)
		return
	}
	if err := w.Write("structWithTag", []struct{ID int `excel:"编号"`}{{1000},{2000}}); err != nil {
		fmt.Println(err)
		return
	}
	if err := w.Write("structWithTagAndIgnore", []struct{
		ID int `excel:"编号"`
		Extra int `excel:"-"`
		Name string `excel:"名称"`
	}{{1000,0,"Coco"},{2000,0,"Apple"}}); err != nil {
		fmt.Println(err)
		return
	} 
	if err := w.SaveTo("dist.xlsx"); err != nil {
		fmt.Println(err)
		return
	}
}

Documentation

Overview

Package exl

Excel binding to struct written in Go.(Only supports Go1.18+)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSheetIndexOutOfRange        = errors.New("exl: sheet index out of range")
	ErrHeaderRowIndexOutOfRange    = errors.New("exl: header row index out of range")
	ErrDataStartRowIndexOutOfRange = errors.New("exl: data start row index out of range")
	ErrNoUnmarshaler               = errors.New("no unmarshaler")
	ErrNoDestinationField          = errors.New("no destination field with matching tag")
)
View Source
var ErrCannotCastUnmarshaler = errors.New("cannot cast to unmarshaler interface")

ErrCannotCastUnmarshaler is returned in case a field technically implements an unmarshaler interface, but casting to it at runtime failed for some reason.

View Source
var ErrNegativeUInt = errors.New("negative integer provided for unsigned field")
View Source
var ErrNoRecognizedFormat = errors.New("no recognized format")
View Source
var ErrOverflow = errors.New("numeric overflow, number is too large for this field")

Functions

func Read

func Read[T ReadConfigurator](reader io.Reader, filterFunc ...func(t T) (add bool)) ([]T, error)

Read io.Reader each row bind to `T`

func ReadBinary

func ReadBinary[T ReadConfigurator](bytes []byte, filterFunc ...func(t T) (add bool)) ([]T, error)

ReadBinary each row bind to `T`

func ReadExcel

func ReadExcel(file string, sheetIndex int, walk func(index int, rows *xlsx.Row)) error

ReadExcel walk func from excel

func ReadFile

func ReadFile[T ReadConfigurator](file string, filterFunc ...func(t T) (add bool)) ([]T, error)

ReadFile each row bind to `T`

func UnmarshalBool added in v1.3.0

func UnmarshalBool(destValue reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func UnmarshalExcelUnmarshaler added in v1.3.0

func UnmarshalExcelUnmarshaler(destField reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func UnmarshalFloat added in v1.3.0

func UnmarshalFloat(destValue reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func UnmarshalInt added in v1.3.0

func UnmarshalInt(destValue reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func UnmarshalString added in v1.3.0

func UnmarshalString(destValue reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func UnmarshalTextUnmarshaler added in v1.3.0

func UnmarshalTextUnmarshaler(destField reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func UnmarshalTime added in v1.3.0

func UnmarshalTime(destValue reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func UnmarshalUInt added in v1.3.0

func UnmarshalUInt(destValue reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func Write

func Write[T WriteConfigurator](file string, ts []T) error

Write defines write []T to excel file

params: file,excel file full path

params: typed parameter T, must be implements exl.Bind

func WriteExcel

func WriteExcel(file string, data [][]string) error

WriteExcel defines write [][]string to excel

params: file, excel file pull path

params: data, write data to excel

func WriteExcelTo added in v1.2.2

func WriteExcelTo(w io.Writer, data [][]string) error

WriteExcelTo defines write [][]string to excel

params: w, the dist writer

params: data, write data to excel

func WriteTo added in v1.2.2

func WriteTo[T WriteConfigurator](w io.Writer, ts []T) error

WriteTo defines write to []T to excel file

params: w, the dist writer

params: typed parameter T, must be implements exl.Bind

Types

type ContentError added in v1.3.0

type ContentError struct {
	FieldErrors  []FieldError
	LimitReached bool
}

func (ContentError) Error added in v1.3.0

func (e ContentError) Error() string

Error implements error.

func (ContentError) Unwrap added in v1.3.0

func (e ContentError) Unwrap() []error

Unwrap Error implements the anonymous unwrap interface used by errors.Unwrap and others.

type ExcelUnmarshalParameters added in v1.3.0

type ExcelUnmarshalParameters struct {
	// See ReadConfig.TrimSpace
	TrimSpace bool
	// See xlsx.File.Date1904
	Date1904 bool
	// See ReadConfig.FallbackDateFormats
	FallbackDateFormats []string
}

type ExcelUnmarshaler added in v1.3.0

type ExcelUnmarshaler interface {
	UnmarshalExcel(cell *xlsx.Cell, params *ExcelUnmarshalParameters) error
}

type FieldError added in v1.3.0

type FieldError struct {
	RowIndex     int // 0-based row index. Printed as 1-based row number in error text.
	ColumnIndex  int // 0-based column index.
	ColumnHeader string
	Err          error
}

func (FieldError) Error added in v1.3.0

func (e FieldError) Error() string

Error implements error.

func (FieldError) Unwrap added in v1.3.0

func (e FieldError) Unwrap() error

Unwrap Error implements the anonymous unwrap interface used by errors.Unwrap and others.

type ReadConfig added in v1.2.1

type ReadConfig struct {
	// The tag name to use when looking for fields in the target struct.
	// Defaults to "excel".
	TagName string
	// The index of the worksheet to be read.
	// Defaults to 0, the first worksheet.
	SheetIndex int
	// The row index at which the column headers are read from.
	// Zero-based, defaults to 0.
	HeaderRowIndex int
	// Start the data reading at this row.
	// The header row counts as row.
	// Zero-based, defaults to 1.
	DataStartRowIndex int
	// Configure the default string unmarshaler to trim space after reading a cell.
	// Does not impact any other default unmarshaler,
	// but is available to custom unmarshalers via ExcelUnmarshalParameters.TrimSpace.
	// Defaults to false.
	TrimSpace bool
	// Fallback date formats for date parsing.
	// If an Excel cell is to be unmarshalled into a date,
	// and that cell is either not formatted as Date or contains raw text
	// (which can happen if Excel does not correctly recognize the date format)
	// then these formats are used in the order specified to try and parse
	// the raw cell value into a date.
	// There are no fallback formats configured by default.
	FallbackDateFormats []string
	// Skip reading columns for which no target field is found.
	// Defaults to true.
	SkipUnknownColumns bool
	// Skip reading columns, if there is a target field,
	// but the target type is unsupported
	// or caused an error when determining the unmarshaler to use.
	// Defaults to false.
	SkipUnknownTypes bool
	// Configure how errors during unmarshalling are handled.
	// Unmarshalling errors are e.g. invalid number formats in the cell,
	// date parsing with invalid input,
	// or attempting to unmarshal non-numeric text into a numeric field.
	// Defaults to UnmarshalErrorAbort.
	UnmarshalErrorHandling UnmarshalErrorHandling
	// If UnmarshalErrorHandling is configured as UnmarshalErrorCollect,
	// this option limits the number of errors which are collected before
	// parsing is aborted.
	// Configure a limit of 0 to collect all errors, without upper limit.
	// Defaults to 10.
	MaxUnmarshalErrors uint64
}

type ReadConfigurator added in v1.2.1

type ReadConfigurator interface{ ReadConfigure(rc *ReadConfig) }

type UnmarshalErrorHandling added in v1.3.0

type UnmarshalErrorHandling uint8
const (
	// UnmarshalErrorIgnore
	// Ignore any errors during unmarshalling
	UnmarshalErrorIgnore UnmarshalErrorHandling = iota
	// UnmarshalErrorAbort
	// Abort reading when encountering the first unmarshalling error
	UnmarshalErrorAbort
	// UnmarshalErrorCollect
	// Collect unmarshalling errors up to a limit, but continue reading.
	// Collected errors are returned as one error at the end, of type
	UnmarshalErrorCollect
)

type UnmarshalExcelFunc added in v1.3.0

type UnmarshalExcelFunc func(destValue reflect.Value, cell *xlsx.Cell, params *ExcelUnmarshalParameters) error

func GetUnmarshalFunc added in v1.3.0

func GetUnmarshalFunc(destField reflect.Value) UnmarshalExcelFunc

type WriteConfig added in v1.2.1

type WriteConfig struct{ SheetName, TagName string }

type WriteConfigurator added in v1.2.1

type WriteConfigurator interface{ WriteConfigure(wc *WriteConfig) }

type Writer added in v1.2.0

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

Writer define a writer for exl

func NewWriter added in v1.2.0

func NewWriter(options ...xlsx.FileOption) *Writer

NewWriter returns new exl writer

func (*Writer) SaveTo added in v1.2.0

func (w *Writer) SaveTo(path string) (err error)

SaveTo the buffered binary into dist file

func (*Writer) Write added in v1.2.0

func (w *Writer) Write(sheet string, data any) error

Write or append the param data into sheet

func (*Writer) WriteTo added in v1.2.0

func (w *Writer) WriteTo(dw io.Writer) (n int, err error)

WriteTo the buffered binary into new writer

Jump to

Keyboard shortcuts

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