xlsx: github.com/tealeg/xlsx Index | Examples | Files

package xlsx

import "github.com/tealeg/xlsx"

Index

Examples

Package Files

cell.go col.go data_validation.go date.go doc.go file.go format_code.go hsl.go lib.go read.go reftable.go row.go sheet.go stream_cell.go stream_file.go stream_file_builder.go stream_style.go style.go templates.go theme.go write.go xmlContentTypes.go xmlSharedStrings.go xmlStyle.go xmlTheme.go xmlWorkbook.go xmlWorksheet.go

Constants

const (
    DataValidationTypeCustom
    DataValidationTypeDate
    DataValidationTypeDecimal

    DataValidationTypeTextLeng
    DataValidationTypeTime
    // DataValidationTypeWhole Integer
    DataValidationTypeWhole
)

Data validation types

const (
    DataValidationOperatorBetween
    DataValidationOperatorEqual
    DataValidationOperatorGreaterThan
    DataValidationOperatorGreaterThanOrEqual
    DataValidationOperatorLessThan
    DataValidationOperatorLessThanOrEqual
    DataValidationOperatorNotBetween
    DataValidationOperatorNotEqual
)

Data validation operators

const (
    MJD_0      float64 = 2400000.5
    MJD_JD2000 float64 = 51544.5
)
const (
    GeneralFormat              = 0
    IntegerFormat              = 1
    DecimalFormat              = 2
    DateFormat_dd_mm_yy        = 14
    DateTimeFormat_d_m_yy_h_mm = 22
)
const (
    Helvetica     = "Helvetica"
    Baskerville   = "Baskerville Old Face"
    TimesNewRoman = "Times New Roman"
    Bodoni        = "Bodoni MT"
    GillSans      = "Gill Sans MT"
    Courier       = "Courier"
)

Several popular font names that can be used to create fonts

const (
    RGB_Light_Green = "FFC6EFCE"
    RGB_Dark_Green  = "FF006100"
    RGB_Light_Red   = "FFFFC7CE"
    RGB_Dark_Red    = "FF9C0006"
    RGB_White       = "00000000"
    RGB_Black       = "FFFFFFFF"
)
const ColWidth = 9.5

Default column width in excel

const Excel2006MaxRowCount = 1048576
const Excel2006MaxRowIndex = Excel2006MaxRowCount - 1
const NoRowLimit int = -1
const (
    Solid_Cell_Fill = "solid"
)
const TEMPLATE_DOCPROPS_APP = "" /* 310 byte string literal not displayed */
const TEMPLATE_DOCPROPS_CORE = "" /* 366 byte string literal not displayed */
const TEMPLATE_XL_THEME_THEME = "" /* 10942 byte string literal not displayed */
const TEMPLATE__RELS_DOT_RELS = "" /* 582 byte string literal not displayed */

Variables

var (
    DefaultDateFormat     = builtInNumFmt[14]
    DefaultDateTimeFormat = builtInNumFmt[22]

    DefaultDateOptions = DateTimeOptions{
        Location:        timeLocationUTC,
        ExcelTimeFormat: DefaultDateFormat,
    }

    DefaultDateTimeOptions = DateTimeOptions{
        Location:        timeLocationUTC,
        ExcelTimeFormat: DefaultDateTimeFormat,
    }
)
var (
    NoCurrentSheetError      = errors.New("no Current Sheet")
    WrongNumberOfRowsError   = errors.New("invalid number of cells passed to Write. All calls to Write on the same sheet must have the same number of cells")
    AlreadyOnLastSheetError  = errors.New("NextSheet() called, but already on last sheet")
    UnsupportedCellTypeError = errors.New("the given cell type is not supported")
)
var BuiltStreamFileBuilderError = errors.New("StreamFileBuilder has already been built, functions may no longer be used")
var HSLModel = color.ModelFunc(hslModel)

HSLModel converts any color.Color to a HSL color.

func ColIndexToLetters Uses

func ColIndexToLetters(colRef int) string

ColIndexToLetters is used to convert a zero based, numeric column indentifier into a character code.

func ColLettersToIndex Uses

func ColLettersToIndex(letters string) int

ColLettersToIndex is used to convert a character based column reference to a zero based numeric column identifier.

func FileToSlice Uses

func FileToSlice(path string) ([][][]string, error)

A convenient wrapper around File.ToSlice, FileToSlice will return the raw data contained in an Excel XLSX file as three dimensional slice. The first index represents the sheet number, the second the row number, and the third the cell number.

For example:

var mySlice [][][]string
var value string
mySlice = xlsx.FileToSlice("myXLSX.xlsx")
value = mySlice[0][0][0]

Here, value would be set to the raw value of the cell A1 in the first sheet in the XLSX file.

func FileToSliceUnmerged Uses

func FileToSliceUnmerged(path string) ([][][]string, error)

FileToSliceUnmerged is a wrapper around File.ToSliceUnmerged. It returns the raw data contained in an Excel XLSX file as three dimensional slice. Merged cells will be unmerged. Covered cells become the values of theirs origins.

func GetCellIDStringFromCoords Uses

func GetCellIDStringFromCoords(x, y int) string

GetCellIDStringFromCoords returns the Excel format cell name that represents a pair of zero based cartesian coordinates.

func GetCellIDStringFromCoordsWithFixed Uses

func GetCellIDStringFromCoordsWithFixed(x, y int, xFixed, yFixed bool) string

GetCellIDStringFromCoordsWithFixed returns the Excel format cell name that represents a pair of zero based cartesian coordinates. It can specify either value as fixed.

func GetCoordsFromCellIDString Uses

func GetCoordsFromCellIDString(cellIDString string) (x, y int, error error)

GetCoordsFromCellIDString returns the zero based cartesian coordinates from a cell name in Excel format, e.g. the cellIDString "A1" returns 0, 0 and the "B3" return 1, 2.

func HSLToRGB Uses

func HSLToRGB(h, s, l float64) (r, g, b uint8)

HSLToRGB converts an HSL triple to a RGB triple.

Ported from http://goo.gl/Vg1h9

func MakeDefaultContentTypes Uses

func MakeDefaultContentTypes() (types xlsxTypes)

func NewDataValidation Uses

func NewDataValidation(startRow, startCol, endRow, endCol int, allowBlank bool) *xlsxDataValidation

NewDataValidation return data validation struct

func RGBToHSL Uses

func RGBToHSL(r, g, b uint8) (h, s, l float64)

RGBToHSL converts an RGB triple to a HSL triple.

Ported from http://goo.gl/Vg1h9

func RowIndexToString Uses

func RowIndexToString(rowRef int) string

RowIndexToString is used to convert a zero based, numeric row indentifier into its string representation.

func SetDefaultFont Uses

func SetDefaultFont(size int, name string)

func TimeFromExcelTime Uses

func TimeFromExcelTime(excelTime float64, date1904 bool) time.Time

Convert an excelTime representation (stored as a floating point number) to a time.Time.

func TimeToExcelTime Uses

func TimeToExcelTime(t time.Time, date1904 bool) float64

TimeToExcelTime will convert a time.Time into Excel's float representation, in either 1900 or 1904 mode. If you don't know which to use, set date1904 to false. TODO should this should handle Julian dates?

func TimeToUTCTime Uses

func TimeToUTCTime(t time.Time) time.Time

type Alignment Uses

type Alignment struct {
    Horizontal   string
    Indent       int
    ShrinkToFit  bool
    TextRotation int
    Vertical     string
    WrapText     bool
}

func DefaultAlignment Uses

func DefaultAlignment() *Alignment

type AutoFilter Uses

type AutoFilter struct {
    TopLeftCell     string
    BottomRightCell string
}

type Border Uses

type Border struct {
    Left        string
    LeftColor   string
    Right       string
    RightColor  string
    Top         string
    TopColor    string
    Bottom      string
    BottomColor string
}

Border is a high level structure intended to provide user access to the contents of Border Style within an Sheet.

func DefaultBorder Uses

func DefaultBorder() *Border

func NewBorder Uses

func NewBorder(left, right, top, bottom string) *Border

type Cell Uses

type Cell struct {
    Row   *Row
    Value string

    NumFmt string

    Hidden bool
    HMerge int
    VMerge int

    DataValidation *xlsxDataValidation
    // contains filtered or unexported fields
}

Cell is a high level structure intended to provide user access to the contents of Cell within an xlsx.Row.

func NewCell Uses

func NewCell(r *Row) *Cell

NewCell creates a cell and adds it to a row.

func (*Cell) Bool Uses

func (c *Cell) Bool() bool

Bool returns a boolean from a cell's value. TODO: Determine if the current return value is appropriate for types other than CellTypeBool.

func (*Cell) Float Uses

func (c *Cell) Float() (float64, error)

Float returns the value of cell as a number.

func (*Cell) FormattedValue Uses

func (c *Cell) FormattedValue() (string, error)

FormattedValue returns a value, and possibly an error condition from a Cell. If it is possible to apply a format to the cell value, it will do so, if not then an error will be returned, along with the raw value of the Cell.

func (*Cell) Formula Uses

func (c *Cell) Formula() string

Formula returns the formula string for the cell.

func (*Cell) GeneralNumeric Uses

func (c *Cell) GeneralNumeric() (string, error)

GeneralNumeric returns the value of the cell as a string. It is formatted very closely to the the XLSX spec for how to display values when the storage type is Number and the format type is General. It is not 100% identical to the spec but is as close as you can get using the built in Go formatting tools.

func (*Cell) GeneralNumericWithoutScientific Uses

func (c *Cell) GeneralNumericWithoutScientific() (string, error)

GeneralNumericWithoutScientific returns numbers that are always formatted as numbers, but it does not follow the rules for when XLSX should switch to scientific notation, since sometimes scientific notation is not desired, even if that is how the document is supposed to be formatted.

func (*Cell) GetNumberFormat Uses

func (c *Cell) GetNumberFormat() string

GetNumberFormat returns the number format string for a cell.

func (*Cell) GetStyle Uses

func (c *Cell) GetStyle() *Style

GetStyle returns the Style associated with a Cell

func (*Cell) GetTime Uses

func (c *Cell) GetTime(date1904 bool) (t time.Time, err error)

GetTime returns the value of a Cell as a time.Time

func (*Cell) Int Uses

func (c *Cell) Int() (int, error)

Int returns the value of cell as integer. Has max 53 bits of precision See: float64(int64(math.MaxInt))

func (*Cell) Int64 Uses

func (c *Cell) Int64() (int64, error)

Int64 returns the value of cell as 64-bit integer.

func (*Cell) IsTime Uses

func (c *Cell) IsTime() bool

IsTime returns true if the cell stores a time value.

func (*Cell) Merge Uses

func (c *Cell) Merge(hcells, vcells int)

Merge with other cells, horizontally and/or vertically.

func (*Cell) SetBool Uses

func (c *Cell) SetBool(b bool)

SetBool sets a cell's value to a boolean.

func (*Cell) SetDataValidation Uses

func (c *Cell) SetDataValidation(dd *xlsxDataValidation)

SetDataValidation set data validation

func (*Cell) SetDate Uses

func (c *Cell) SetDate(t time.Time)

SetDate sets the value of a cell to a float.

func (*Cell) SetDateTime Uses

func (c *Cell) SetDateTime(t time.Time)

func (*Cell) SetDateTimeWithFormat Uses

func (c *Cell) SetDateTimeWithFormat(n float64, format string)

func (*Cell) SetDateWithOptions Uses

func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions)

SetDateWithOptions allows for more granular control when exporting dates and times

func (*Cell) SetFloat Uses

func (c *Cell) SetFloat(n float64)

SetFloat sets the value of a cell to a float.

func (*Cell) SetFloatWithFormat Uses

func (c *Cell) SetFloatWithFormat(n float64, format string)

SetFloatWithFormat sets the value of a cell to a float and applies formatting to the cell.

func (*Cell) SetFormat Uses

func (c *Cell) SetFormat(format string)

SetCellFormat set cell value format

func (*Cell) SetFormula Uses

func (c *Cell) SetFormula(formula string)

SetFormula sets the format string for a cell.

func (*Cell) SetInt Uses

func (c *Cell) SetInt(n int)

SetInt sets a cell's value to an integer.

func (*Cell) SetInt64 Uses

func (c *Cell) SetInt64(n int64)

SetInt64 sets a cell's value to a 64-bit integer.

func (*Cell) SetNumeric Uses

func (c *Cell) SetNumeric(s string)

SetNumeric sets a cell's value to a number

func (*Cell) SetString Uses

func (c *Cell) SetString(s string)

SetString sets the value of a cell to a string.

func (*Cell) SetStringFormula Uses

func (c *Cell) SetStringFormula(formula string)

func (*Cell) SetStyle Uses

func (c *Cell) SetStyle(style *Style)

SetStyle sets the style of a cell.

func (*Cell) SetValue Uses

func (c *Cell) SetValue(n interface{})

SetInt sets a cell's value to an integer.

func (*Cell) String Uses

func (c *Cell) String() string

String returns the value of a Cell as a string. If you'd like to see errors returned from formatting then please use Cell.FormattedValue() instead.

func (*Cell) Type Uses

func (c *Cell) Type() CellType

Type returns the CellType of a cell. See CellType constants for more details.

type CellInterface Uses

type CellInterface interface {
    String() string
    FormattedValue() string
}

CellInterface defines the public API of the Cell.

type CellType Uses

type CellType int

CellType is an int type for storing metadata about the data type in the cell.

const (
    CellTypeString CellType = iota
    // CellTypeStringFormula is a specific format for formulas that return string values. Formulas that return numbers
    // and booleans are stored as those types.
    CellTypeStringFormula
    CellTypeNumeric
    CellTypeBool
    // CellTypeInline is not respected on save, all inline string cells will be saved as SharedStrings
    // when saving to an XLSX file. This the same behavior as that found in Excel.
    CellTypeInline
    CellTypeError
    // d (Date): Cell contains a date in the ISO 8601 format.
    // That is the only mention of this format in the XLSX spec.
    // Date seems to be unused by the current version of Excel, it stores dates as Numeric cells with a date format string.
    // For now these cells will have their value output directly. It is unclear if the value is supposed to be parsed
    // into a number and then formatted using the formatting or not.
    CellTypeDate
)

These are the cell types from the ST_CellType spec

func (CellType) Ptr Uses

func (ct CellType) Ptr() *CellType

type Col Uses

type Col struct {
    Min          int
    Max          int
    Hidden       bool
    Width        float64
    Collapsed    bool
    OutlineLevel uint8
    BestFit      bool
    CustomWidth  bool
    Phonetic     bool
    // contains filtered or unexported fields
}

func NewColForRange Uses

func NewColForRange(min, max int) *Col

NewColForRange return a pointer to a new Col, which will apply to columns in the range min to max (inclusive). Note, in order for this Col to do anything useful you must set some of its parameters and then apply it to a Sheet by calling sheet.SetColParameters.

func (*Col) GetStreamStyle Uses

func (c *Col) GetStreamStyle() StreamStyle

func (*Col) GetStyle Uses

func (c *Col) GetStyle() *Style

GetStyle returns the Style associated with a Col

func (*Col) SetOutlineLevel Uses

func (c *Col) SetOutlineLevel(outlineLevel uint8)

func (*Col) SetStreamStyle Uses

func (c *Col) SetStreamStyle(style StreamStyle)

SetStreamStyle sets the style and number format id to the ones specified in the given StreamStyle

func (*Col) SetStyle Uses

func (c *Col) SetStyle(style *Style)

SetStyle sets the style of a Col

func (*Col) SetType Uses

func (c *Col) SetType(cellType CellType)

SetType will set the format string of a column based on the type that you want to set it to. This function does not really make a lot of sense.

func (*Col) SetWidth Uses

func (c *Col) SetWidth(width float64)

SetWidth sets the width of columns that have this Col applied to them. The width is expressed as the number of characters of the maximum digit width of the numbers 0-9 as rendered in the normal style's font.

type ColStore Uses

type ColStore struct {
    Root *ColStoreNode
    Len  int
}

ColStore is the working store of Col definitions, it will simplify all Cols added to it, to ensure there ar no overlapping definitions.

func (*ColStore) Add Uses

func (cs *ColStore) Add(col *Col) *ColStoreNode

Add a Col to the ColStore. If it overwrites all, or part of some existing Col's range of columns the that Col will be adjusted and/or split to make room for the new Col.

func (*ColStore) FindColByIndex Uses

func (cs *ColStore) FindColByIndex(index int) *Col

func (*ColStore) ForEach Uses

func (cs *ColStore) ForEach(fn func(idx int, col *Col))

ForEach calls the function fn for each Col defined in the ColStore.

type ColStoreNode Uses

type ColStoreNode struct {
    Col  *Col
    Prev *ColStoreNode
    Next *ColStoreNode
}

type DataValidationErrorStyle Uses

type DataValidationErrorStyle int
const (
    StyleStop DataValidationErrorStyle
    StyleWarning
    StyleInformation
)

Data validation error styles

type DataValidationOperator Uses

type DataValidationOperator int

DataValidationOperator operator enum

type DataValidationType Uses

type DataValidationType int

type DateTimeOptions Uses

type DateTimeOptions struct {
    // Location allows calculating times in other timezones/locations
    Location *time.Location
    // ExcelTimeFormat is the string you want excel to use to format the datetime
    ExcelTimeFormat string
}

DateTimeOptions are additional options for exporting times

type File Uses

type File struct {
    Date1904 bool

    Sheets []*Sheet
    Sheet  map[string]*Sheet

    DefinedNames []*xlsxDefinedName
    // contains filtered or unexported fields
}

File is a high level structure providing a slice of Sheet structs to the user.

func NewFile Uses

func NewFile() *File

Create a new File

func OpenBinary Uses

func OpenBinary(bs []byte) (*File, error)

OpenBinary() take bytes of an XLSX file and returns a populated xlsx.File struct for it.

func OpenBinaryWithRowLimit Uses

func OpenBinaryWithRowLimit(bs []byte, rowLimit int) (*File, error)

OpenBinaryWithRowLimit() take bytes of an XLSX file and returns a populated xlsx.File struct for it.

func OpenFile Uses

func OpenFile(fileName string) (file *File, err error)

OpenFile() take the name of an XLSX file and returns a populated xlsx.File struct for it.

func OpenFileWithRowLimit Uses

func OpenFileWithRowLimit(fileName string, rowLimit int) (file *File, err error)

OpenFileWithRowLimit() will open the file, but will only read the specified number of rows. If you save this file, it will be truncated to the number of rows specified.

func OpenReaderAt Uses

func OpenReaderAt(r io.ReaderAt, size int64) (*File, error)

OpenReaderAt() take io.ReaderAt of an XLSX file and returns a populated xlsx.File struct for it.

func OpenReaderAtWithRowLimit Uses

func OpenReaderAtWithRowLimit(r io.ReaderAt, size int64, rowLimit int) (*File, error)

OpenReaderAtWithRowLimit() take io.ReaderAt of an XLSX file and returns a populated xlsx.File struct for it.

func ReadZip Uses

func ReadZip(f *zip.ReadCloser) (*File, error)

ReadZip() takes a pointer to a zip.ReadCloser and returns a xlsx.File struct populated with its contents. In most cases ReadZip is not used directly, but is called internally by OpenFile.

func ReadZipReader Uses

func ReadZipReader(r *zip.Reader) (*File, error)

ReadZipReader() can be used to read an XLSX in memory without touching the filesystem.

func ReadZipReaderWithRowLimit Uses

func ReadZipReaderWithRowLimit(r *zip.Reader, rowLimit int) (*File, error)

ReadZipReaderWithRowLimit() can be used to read an XLSX in memory without touching the filesystem. rowLimit is the number of rows that should be read from the file. If rowLimit is -1, no limit is applied. You can specify this with the constant NoRowLimit.

func ReadZipWithRowLimit Uses

func ReadZipWithRowLimit(f *zip.ReadCloser, rowLimit int) (*File, error)

ReadZipWithRowLimit() takes a pointer to a zip.ReadCloser and returns a xlsx.File struct populated with its contents. In most cases ReadZip is not used directly, but is called internally by OpenFile.

func (*File) AddSheet Uses

func (f *File) AddSheet(sheetName string) (*Sheet, error)

AddSheet Add a new Sheet, with the provided name, to a File. The minimum sheet name length is 1 character. If the sheet name length is less an error is thrown. The maximum sheet name length is 31 characters. If the sheet name length is exceeded an error is thrown. These special characters are also not allowed: : \ / ? * [ ]

func (*File) AppendSheet Uses

func (f *File) AppendSheet(sheet Sheet, sheetName string) (*Sheet, error)

Appends an existing Sheet, with the provided name, to a File

func (*File) MarshallParts Uses

func (f *File) MarshallParts() (map[string]string, error)

Construct a map of file name to XML content representing the file in terms of the structure of an XLSX file.

func (*File) Save Uses

func (f *File) Save(path string) (err error)

Save the File to an xlsx file at the provided path.

func (*File) ToSlice Uses

func (f *File) ToSlice() (output [][][]string, err error)

Return the raw data contained in the File as three dimensional slice. The first index represents the sheet number, the second the row number, and the third the cell number.

For example:

var mySlice [][][]string
var value string
mySlice = xlsx.FileToSlice("myXLSX.xlsx")
value = mySlice[0][0][0]

Here, value would be set to the raw value of the cell A1 in the first sheet in the XLSX file.

func (*File) ToSliceUnmerged Uses

func (f *File) ToSliceUnmerged() (output [][][]string, err error)

ToSliceUnmerged returns the raw data contained in the File as three dimensional slice (s. method ToSlice). A covered cell become the value of its origin cell. Example: table where A1:A2 merged. | 01.01.2011 | Bread | 20 | | | Fish | 70 | This sheet will be converted to the slice: [ [01.01.2011 Bread 20]

[01.01.2011 Fish 70] ]

func (*File) Write Uses

func (f *File) Write(writer io.Writer) (err error)

Write the File to io.Writer as xlsx

type Fill Uses

type Fill struct {
    PatternType string
    BgColor     string
    FgColor     string
}

Fill is a high level structure intended to provide user access to the contents of background and foreground color index within an Sheet.

var (
    FillGreen *Fill
    FillRed   *Fill
    FillWhite *Fill
)

func DefaultFill Uses

func DefaultFill() *Fill

func NewFill Uses

func NewFill(patternType, fgColor, bgColor string) *Fill

type Font Uses

type Font struct {
    Size      int
    Name      string
    Family    int
    Charset   int
    Color     string
    Bold      bool
    Italic    bool
    Underline bool
}
var (
    FontBold       *Font
    FontItalic     *Font
    FontUnderlined *Font
)

func DefaultFont Uses

func DefaultFont() *Font

func NewFont Uses

func NewFont(size int, name string) *Font

type HSL Uses

type HSL struct {
    H, S, L float64
}

HSL represents a cylindrical coordinate of points in an RGB color model.

Values are in the range 0 to 1.

func (HSL) RGBA Uses

func (c HSL) RGBA() (uint32, uint32, uint32, uint32)

RGBA returns the alpha-premultiplied red, green, blue and alpha values for the HSL.

type Pane Uses

type Pane struct {
    XSplit      float64
    YSplit      float64
    TopLeftCell string
    ActivePane  string
    State       string // Either "split" or "frozen"
}

type RefTable Uses

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

func MakeSharedStringRefTable Uses

func MakeSharedStringRefTable(source *xlsxSST) *RefTable

MakeSharedStringRefTable() takes an xlsxSST struct and converts it's contents to an slice of strings used to refer to string values by numeric index - this is the model used within XLSX worksheet (a numeric reference is stored to a shared cell value).

func NewSharedStringRefTable Uses

func NewSharedStringRefTable() *RefTable

NewSharedStringRefTable() creates a new, empty RefTable.

func (*RefTable) AddString Uses

func (rt *RefTable) AddString(str string) int

AddString adds a string to the reference table and return it's numeric index. If the string already exists then it simply returns the existing index.

func (*RefTable) Length Uses

func (rt *RefTable) Length() int

func (*RefTable) ResolveSharedString Uses

func (rt *RefTable) ResolveSharedString(index int) string

Resolvesharedstring() looks up a string value by numeric index from a provided reference table (just a slice of strings in the correct order). This function only exists to provide clarity or purpose via it's name.

type Row Uses

type Row struct {
    Cells        []*Cell
    Hidden       bool
    Sheet        *Sheet
    Height       float64
    OutlineLevel uint8
    // contains filtered or unexported fields
}

func (*Row) AddCell Uses

func (r *Row) AddCell() *Cell

func (*Row) ReadStruct Uses

func (r *Row) ReadStruct(ptr interface{}) error

ReadStruct reads a struct from r to ptr. Accepts a ptr to struct. This code expects a tag xlsx:"N", where N is the index of the cell to be used. Basic types like int,string,float64 and bool are supported

Code:

//example type
type structTest struct {
    IntVal     int     `xlsx:"0"`
    StringVal  string  `xlsx:"1"`
    FloatVal   float64 `xlsx:"2"`
    IgnoredVal int     `xlsx:"-"`
    BoolVal    bool    `xlsx:"4"`
}
structVal := structTest{
    IntVal:     16,
    StringVal:  "heyheyhey :)!",
    FloatVal:   3.14159216,
    IgnoredVal: 7,
    BoolVal:    true,
}
//create a new xlsx file and write a struct
//in a new row
f := NewFile()
sheet, _ := f.AddSheet("TestRead")
row := sheet.AddRow()
row.WriteStruct(&structVal, -1)

//read the struct from the same row
readStruct := &structTest{}
err := row.ReadStruct(readStruct)
if err != nil {
    panic(err)
}
fmt.Println(readStruct)

func (*Row) SetHeight Uses

func (r *Row) SetHeight(ht float64)

func (*Row) SetHeightCM Uses

func (r *Row) SetHeightCM(ht float64)

func (*Row) WriteSlice Uses

func (r *Row) WriteSlice(e interface{}, cols int) int

Writes an array to row r. Accepts a pointer to array type 'e', and writes the number of columns to write, 'cols'. If 'cols' is < 0, the entire array will be written if possible. Returns -1 if the 'e' doesn't point to an array, otherwise the number of columns written.

func (*Row) WriteStruct Uses

func (r *Row) WriteStruct(e interface{}, cols int) int

Writes a struct to row r. Accepts a pointer to struct type 'e', and the number of columns to write, `cols`. If 'cols' is < 0, the entire struct will be written if possible. Returns -1 if the 'e' doesn't point to a struct, otherwise the number of columns written

type Sheet Uses

type Sheet struct {
    Name            string
    File            *File
    Rows            []*Row
    Cols            *ColStore
    MaxRow          int
    MaxCol          int
    Hidden          bool
    Selected        bool
    SheetViews      []SheetView
    SheetFormat     SheetFormat
    AutoFilter      *AutoFilter
    DataValidations []*xlsxDataValidation
}

Sheet is a high level structure intended to provide user access to the contents of a particular sheet within an XLSX file.

func (*Sheet) AddDataValidation Uses

func (s *Sheet) AddDataValidation(dv *xlsxDataValidation)

Add a DataValidation to a range of cells

func (*Sheet) AddRow Uses

func (s *Sheet) AddRow() *Row

Add a new Row to a Sheet

func (*Sheet) AddRowAtIndex Uses

func (s *Sheet) AddRowAtIndex(index int) (*Row, error)

Add a new Row to a Sheet at a specific index

func (*Sheet) Cell Uses

func (sh *Sheet) Cell(row, col int) *Cell

Get a Cell by passing it's cartesian coordinates (zero based) as row and column integer indexes.

For example:

cell := sheet.Cell(0,0)

... would set the variable "cell" to contain a Cell struct containing the data from the field "A1" on the spreadsheet.

func (*Sheet) Col Uses

func (s *Sheet) Col(idx int) *Col

Return the Col that applies to this Column index, or return nil if no such Col exists

func (*Sheet) RemoveRowAtIndex Uses

func (s *Sheet) RemoveRowAtIndex(index int) error

Removes a row at a specific index

func (*Sheet) Row Uses

func (s *Sheet) Row(idx int) *Row

Make sure we always have as many Rows as we do cells.

func (*Sheet) SetColParameters Uses

func (s *Sheet) SetColParameters(col *Col)

Set the parameters of a column. Parameters are passed as a pointer to a Col structure which you much construct yourself.

func (*Sheet) SetColWidth Uses

func (s *Sheet) SetColWidth(min, max int, width float64)

Set the width of a range of columns.

func (*Sheet) SetOutlineLevel Uses

func (s *Sheet) SetOutlineLevel(minCol, maxCol int, outlineLevel uint8)

Set the outline level for a range of columns.

func (*Sheet) SetType Uses

func (s *Sheet) SetType(minCol, maxCol int, cellType CellType)

Set the type for a range of columns.

type SheetFormat Uses

type SheetFormat struct {
    DefaultColWidth  float64
    DefaultRowHeight float64
    OutlineLevelCol  uint8
    OutlineLevelRow  uint8
}

type SheetView Uses

type SheetView struct {
    Pane *Pane
}

type StreamCell Uses

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

StreamCell holds the data, style and type of cell for streaming.

func NewDateStreamCell Uses

func NewDateStreamCell(t time.Time) StreamCell

NewDateStreamCell creates a new cell that holds a date value and is formatted as dd-mm-yyyy and is of type numeric.

func NewIntegerStreamCell Uses

func NewIntegerStreamCell(cellData int) StreamCell

NewIntegerStreamCell creates a new cell that holds an integer value (represented as string), is formatted as a standard integer and is of type numeric.

func NewStreamCell Uses

func NewStreamCell(cellData string, cellStyle StreamStyle, cellType CellType) StreamCell

NewStreamCell creates a new cell containing the given data with the given style and type.

func NewStringStreamCell Uses

func NewStringStreamCell(cellData string) StreamCell

NewStringStreamCell creates a new cell that holds string data, is of type string and uses general formatting.

func NewStyledIntegerStreamCell Uses

func NewStyledIntegerStreamCell(cellData int, cellStyle StreamStyle) StreamCell

NewStyledIntegerStreamCell creates a new cell that holds an integer value (represented as string) and is styled according to the given style.

func NewStyledStringStreamCell Uses

func NewStyledStringStreamCell(cellData string, cellStyle StreamStyle) StreamCell

NewStyledStringStreamCell creates a new cell that holds a string and is styled according to the given style.

type StreamFile Uses

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

func (*StreamFile) Close Uses

func (sf *StreamFile) Close() error

Close closes the Stream File. Any sheets that have not yet been written to will have an empty sheet created for them.

func (*StreamFile) Error Uses

func (sf *StreamFile) Error() error

Error reports any error that has occurred during a previous Write or Flush.

func (*StreamFile) Flush Uses

func (sf *StreamFile) Flush()

func (*StreamFile) NextSheet Uses

func (sf *StreamFile) NextSheet() error

NextSheet will switch to the next sheet. Sheets are selected in the same order they were added. Once you leave a sheet, you cannot return to it.

func (*StreamFile) Write Uses

func (sf *StreamFile) Write(cells []string) error

Write will write a row of cells to the current sheet. Every call to Write on the same sheet must contain the same number of cells as the header provided when the sheet was created or an error will be returned. This function will always trigger a flush on success. Currently the only supported data type is string data.

func (*StreamFile) WriteAll Uses

func (sf *StreamFile) WriteAll(records [][]string) error

func (*StreamFile) WriteAllS Uses

func (sf *StreamFile) WriteAllS(records [][]StreamCell) error

WriteAllS will write all the rows provided in records. All rows must have the same number of cells as the number of columns given when creating the sheet. This function will always trigger a flush on success. WriteAllS supports all data types and styles that are supported by StreamCell.

func (*StreamFile) WriteS Uses

func (sf *StreamFile) WriteS(cells []StreamCell) error

WriteS will write a row of cells to the current sheet. Every call to WriteS on the same sheet must contain the same number of cells as the number of columns provided when the sheet was created or an error will be returned. This function will always trigger a flush on success. WriteS supports all data types and styles that are supported by StreamCell.

func (*StreamFile) WriteWithColumnDefaultMetadata Uses

func (sf *StreamFile) WriteWithColumnDefaultMetadata(cells []string) error

WriteWithColumnDefaultMetadata will write a row of cells to the current sheet. Every call to WriteWithColumnDefaultMetadata on the same sheet must contain the same number of cells as the header provided when the sheet was created or an error will be returned. This function will always trigger a flush on success. Each cell will be encoded with the default StreamingCellMetadata of the column that it belongs to. However, if the cell data string cannot be parsed into the cell type in StreamingCellMetadata, we fall back on encoding the cell as a string and giving it a default string style

type StreamFileBuilder Uses

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

func NewStreamFileBuilder Uses

func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder

NewStreamFileBuilder creates an StreamFileBuilder that will write to the the provided io.writer

func NewStreamFileBuilderForPath Uses

func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error)

NewStreamFileBuilderForPath takes the name of an XLSX file and returns a builder for it. The file will be created if it does not exist, or truncated if it does.

func (*StreamFileBuilder) AddSheet Uses

func (sb *StreamFileBuilder) AddSheet(name string, cellTypes []*CellType) error

AddSheet will add sheets with the given name with the provided headers. The headers cannot be edited later, and all rows written to the sheet must contain the same number of cells as the header. Sheet names must be unique, or an error will be thrown.

func (*StreamFileBuilder) AddSheetS Uses

func (sb *StreamFileBuilder) AddSheetS(name string, columnStyles []StreamStyle) error

AddSheetS will add a sheet with the given name and column styles. The number of column styles given is the number of columns that will be created, and thus the number of cells each row has to have. columnStyles[0] becomes the style of the first column, columnStyles[1] the style of the second column etc. All the styles in columnStyles have to have been added or an error will be returned. Sheet names must be unique, or an error will be returned.

func (*StreamFileBuilder) AddSheetWithDefaultColumnMetadata Uses

func (sb *StreamFileBuilder) AddSheetWithDefaultColumnMetadata(name string, columnsDefaultStreamingCellMetadata []*StreamingCellMetadata) error

func (*StreamFileBuilder) AddStreamStyle Uses

func (sb *StreamFileBuilder) AddStreamStyle(streamStyle StreamStyle) error

AddStreamStyle adds a new style to the style sheet. Only Styles that have been added through this function will be usable. This function cannot be used after AddSheetS or Build has been called, and if it is called after AddSheetS or Buildit will return an error.

func (*StreamFileBuilder) AddStreamStyleList Uses

func (sb *StreamFileBuilder) AddStreamStyleList(streamStyles []StreamStyle) error

AddStreamStyleList adds a list of new styles to the style sheet. Only Styles that have been added through either this function or AddStreamStyle will be usable. This function cannot be used after AddSheetS and Build has been called, and if it is called after AddSheetS and Build it will return an error.

func (*StreamFileBuilder) AddValidation Uses

func (sb *StreamFileBuilder) AddValidation(sheetIndex int, validation *xlsxDataValidation)

AddValidation will add a validation to a sheet.

func (*StreamFileBuilder) Build Uses

func (sb *StreamFileBuilder) Build() (*StreamFile, error)

Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct that can be used to write the rows to the sheets.

type StreamStyle Uses

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

StreamStyle has style and formatting information. Used to store a style for streaming

var (
    StreamStyleFromColumn StreamStyle

    StreamStyleDefaultString    StreamStyle
    StreamStyleBoldString       StreamStyle
    StreamStyleItalicString     StreamStyle
    StreamStyleUnderlinedString StreamStyle

    StreamStyleDefaultInteger    StreamStyle
    StreamStyleBoldInteger       StreamStyle
    StreamStyleItalicInteger     StreamStyle
    StreamStyleUnderlinedInteger StreamStyle

    StreamStyleDefaultDate StreamStyle

    StreamStyleDefaultDecimal StreamStyle
)

func MakeDateStyle Uses

func MakeDateStyle(font *Font, fill *Fill, alignment *Alignment, border *Border) StreamStyle

MakeDateStyle creates a new style that can be used on cells with Date data. The formatting used is: dd_mm_yy If used on other data the formatting might be wrong.

func MakeDecimalStyle Uses

func MakeDecimalStyle(font *Font, fill *Fill, alignment *Alignment, border *Border) StreamStyle

MakeDecimalStyle creates a new style that can be used on cells with decimal numeric data. If used on other data the formatting might be wrong.

func MakeIntegerStyle Uses

func MakeIntegerStyle(font *Font, fill *Fill, alignment *Alignment, border *Border) StreamStyle

MakeIntegerStyle creates a new style that can be used on cells with integer data. If used on other data the formatting might be wrong.

func MakeStringStyle Uses

func MakeStringStyle(font *Font, fill *Fill, alignment *Alignment, border *Border) StreamStyle

MakeStringStyle creates a new style that can be used on cells with string data. If used on other data the formatting might be wrong.

func MakeStyle Uses

func MakeStyle(numFormatId int, font *Font, fill *Fill, alignment *Alignment, border *Border) StreamStyle

MakeStyle creates a new StreamStyle and add it to the styles that will be streamed.

type StreamingCellMetadata Uses

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

StreamingCellMetadata represents anything attributable to a cell except for the cell data itself. For example, it is used in StreamFileBuilder.AddSheetWithDefaultColumnMetadata to associate default attributes for cells in a particular column

var (
    DefaultStringStreamingCellMetadata  StreamingCellMetadata
    DefaultNumericStreamingCellMetadata StreamingCellMetadata
    DefaultDecimalStreamingCellMetadata StreamingCellMetadata
    DefaultIntegerStreamingCellMetadata StreamingCellMetadata
    DefaultDateStreamingCellMetadata    StreamingCellMetadata
)

func MakeStreamingCellMetadata Uses

func MakeStreamingCellMetadata(cellType CellType, streamStyle StreamStyle) StreamingCellMetadata

func (StreamingCellMetadata) Ptr Uses

func (cm StreamingCellMetadata) Ptr() *StreamingCellMetadata

type Style Uses

type Style struct {
    Border          Border
    Fill            Fill
    Font            Font
    ApplyBorder     bool
    ApplyFill       bool
    ApplyFont       bool
    ApplyAlignment  bool
    Alignment       Alignment
    NamedStyleIndex *int
}

Style is a high level structure intended to provide user access to the contents of Style within an XLSX file.

func NewStyle Uses

func NewStyle() *Style

Return a new Style structure initialised with the default values.

type WorkBookRels Uses

type WorkBookRels map[string]string

func (*WorkBookRels) MakeXLSXWorkbookRels Uses

func (w *WorkBookRels) MakeXLSXWorkbookRels() xlsxWorkbookRels

type XLSXReaderError Uses

type XLSXReaderError struct {
    Err string
}

XLSXReaderError is the standard error type for otherwise undefined errors in the XSLX reading process.

func (*XLSXReaderError) Error Uses

func (e *XLSXReaderError) Error() string

Error returns a string value from an XLSXReaderError struct in order that it might comply with the builtin.error interface.

type XLSXUnmarshaler Uses

type XLSXUnmarshaler interface {
    Unmarshal(*Row) error
}

XLSXUnmarshaler is the interface implemented for types that can unmarshal a Row as a representation of themselves.

Package xlsx imports 17 packages (graph) and is imported by 203 packages. Updated 2019-10-21. Refresh now. Tools for package owners.