Go (golang) library for reading and writing XLSX files.

Related tags

Data Structures xlsx
Overview

XLSX

https://img.shields.io/travis/tealeg/xlsx/master.svg?style=flat-square https://codecov.io/gh/tealeg/xlsx/branch/master/graph/badge.svg https://godoc.org/github.com/tealeg/xlsx?status.svg https://img.shields.io/badge/license-bsd-orange.svg

Introduction

xlsx is a library to simplify reading and writing the XML format used by recent version of Microsoft Excel in Go programs.

Tutorial

If you’d like an introduction to this project try the new tutorial.

Different versions of this project

Prior to v1.0.0

You don’t want these versions ;-)

It’s hard to remember exactly, but work on this library started within a month of the first public announcement of Go, now more than a decade ago. It was essentially a quick hack to get data out of XLSX files at my workplace. Nobody but me relied on it, so it was fine to use this brand new language for this task. Somewhat later I decided to share the code, and I know it was well established as an open-source project by the time I left that job in late 2011.

Although I did do some “release” tags, versioning in Go in the early days relied on tagging your code with the name of the Go release (i.e. go1.2) and then `go get` would fetch that tag, if it existed, and if not, it’d grab the master branch.

Version 1.x.x

Version 1.0.0 was tagged in 2017 to support vendoring tools.

As of October 8th, 2019, I’ve branched off v1.x.x maintenance work from master. The master branch now tracks v2.x.x.

If you have existing code, can live with the issues in the 1.x.x codebase, and don’t want to update your code to use a later version, then you can stick to these releases. I mostly won’t be touching this code, but if something really important comes up, let me know.

Version 2.x.x

Version 2.0.0 introduced breaking changes in the API.

The scope of these changes included the way `Col` elements and `DataValidation` works, as these aspects have been built around incorrect models of the underlying XLSX format.

See the https://github.com/tealeg/xlsx/milestone/5 for details.

Version 2.0.1 was tagged purely because 2.0.0 wasn’t handled correctly with regards to how go modules work. It isn’t possible to use 2.0.0 from a Go Modules based project.

Version 3.x.x

Version 3.0.0 introduces some more breaking changes in the API. All methods that can return an `xlsx.File` struct now accept zero, one or many `xlsx.FileOption` functions as their final arguments. These can be used to modify the behaviour of the resultant struct - in particular they replace the `…WithRowLimit` variants of those methods with the result of calling `xlsx.RowLimit` and they add the ability to define a custom backing store for the spreadsheet data to be held in whilst processing.

StreamFileBuilder has been dropped from this version of the library as it has become difficult to maintain.

Full API docs

The full API docs can be viewed using go’s built in documentation tool, or online at godoc.org.

Contributing

We’re extremely happy to review pull requests. Please be patient, maintaining XLSX doesn’t pay anyone’s salary (to my knowledge).

If you’d like to propose a change please ensure the following:

Eat a peach - Geoff

Issues
  • Writer gives broken Excel File

    Writer gives broken Excel File

    Using the following file with version d6607c512cf8c1083a9b5ec1efd7e1ccfb1832c8 I get a broken Excel file. How can I write multiple rows?

    package main
    
    import (
        "fmt"
        "github.com/tealeg/xlsx"
    )
    
    func main() {
        var file *xlsx.File
        var sheet *xlsx.Sheet
        var row *xlsx.Row
        var cell *xlsx.Cell
        var err error
    
        file = xlsx.NewFile()
        sheet = file.AddSheet("Sheet1")
        row = sheet.AddRow()
        cell = row.AddCell()
        cell.Value = "I am a cell!"
    
        row = sheet.AddRow()
        cell = row.AddCell()
        cell.Value = "I am a cell!"
    
        err = file.Save("MyXLSXFile.xlsx")
    
        if err != nil {
            fmt.Printf(err.Error())
        }
    }
    
    opened by pgundlach 40
  • XLSX files produced by this library need repair by Excel.

    XLSX files produced by this library need repair by Excel.

    Excel 2013 is prone to give this warning: "We found a problem with some content in [generated file name.xlsx. Do you want us to try to recover as much as we can ?" But nothing appears to be broken - the generated data had made its way into the file.

    I suspect this issue is due to the incomplete style information exported currently.

    opened by tealeg 31
  • Added merge cell borders

    Added merge cell borders

    We originally had both custom column width and merge cell borders in this patch, but coincidentally someone else did a custom column width patch, so we had to deal with that conflict.

    in progress 
    opened by greenenergy 30
  • A date cell but get a number

    A date cell but get a number

    I write a date cell "2012/11/8" in Excel. And use this lib cell.String() to read it and shows 41221.

    opened by dlintw 18
  • Interrupting a program without saving a file corrupts it / no close function

    Interrupting a program without saving a file corrupts it / no close function

    This is not the issue by itself, the issue is that I HAVE to call Save() to properly close a file while I could be willing to discard it upon program interruption, for example with defer file.Close(). We need a proper function on the File struct to close it without saving.

    triaged no-issue-activity 
    opened by tbourvon 16
  • Proposal: add method for reading structs from rows

    Proposal: add method for reading structs from rows

    Problem

    Reading structs from a row which has a well-known structure is a bit repetitive, because you will have to iter over the cells, check for the desired type to be obtained, checking for errors and filling the struct.

    Current approach

    If you want to read a whole file (or a single sheet) and convert it to a slice of structs, you have to take any of these two paths:

    • Use FileToSlice iter over the slices and handle the type-casting for yourself
    • Iter over the Sheets of the file, then over the rows and filling the structs by yourself

    Proposal

    Currently we have a method in *Row to Write a struct , so maybe we can define a symmetric method like (*Row).ReadStruct(interface{}) error that receives a struct pointer to be filled.

    To know the relation column <-> field we can use struct tags that defines the index of the cell to be dumped in the field, like so:

    type structTest struct {
    	IntVal     int     `xlsx:"0"`
    	StringVal  string  `xlsx:"1"`
    	FloatVal   float64 `xlsx:"2"`
    	IgnoredVal int     `xlsx:"-"`
    	BoolVal    bool    `xlsx:"4"`
    }
    

    I'm wondering if would be better to use a name for the column, but I sincerely don't know how this would work.

    I have a very simple implementation of the proposal using the tags in a forked repo:

    Implementation commit

    Comments are welcome!

    no-issue-activity 
    opened by thewraven 16
  • Opening an xlsx file and saving it as another xlsx file creates an invalid file

    Opening an xlsx file and saving it as another xlsx file creates an invalid file

    package main
    
    import (
        "fmt"
        "github.com/tealeg/xlsx"
    )
    
    func main() {
        var file *xlsx.File
        var err error
    
        file, err = xlsx.OpenFile("/path/to/file.xlsx")
        err = file.Save("/path/to/anotherFile.xlsx")
        if err != nil {
            fmt.Printf(err.Error())
        }
    }
    

    The above code compiles and runs fine. It creates anotherFile.xlsx but when opening this file Excel application crashes.

    in progress 
    opened by manuviswam 15
  • Border style not allowed to be empty

    Border style not allowed to be empty

    https://github.com/tealeg/xlsx/commit/27f0f707d42799573616e9166c4be707dd4d2621 introduced a fix for merged cells AFAIK but introduced a regression which created borders styles with attribute empty string, which is not definition compliant. Value must be one of {'double', 'mediumDashDot', 'mediumDashDotDot', 'hair', 'dashDot', 'slantDashDot', 'medium', 'thick', 'mediumDashed', 'dashDotDot', 'thin', 'dotted', 'dashed'}

    waiting for confirmation from user 
    opened by djui 15
  • XLSX Style doesn't work

    XLSX Style doesn't work

    Hi, I'm using the XLSX style, e.g Fill style in a Cell, I set cell.SetStyle(style) where style is fill := NewFill("solid", "#12CDD3", "#FFFFFF"); style.Fill = *fill, but it does not show any fill color in the generated XLSX file, Am I using the style the right way, what I was missing here? I set ApplyFill to true by the way. ;-) Thanks

    waiting for confirmation from user 
    opened by forhappy 15
  • Need another release~

    Need another release~

    The last release 1.0.3 was released in 2017, is there any plan to release a new version, like 1.0.4 or 1.1.0? There is a lot of commits merged to master since 2017.

    opened by sleagon 14
  • fix cell regex expression match f tag in a cell

    fix cell regex expression match f tag in a cell

    issue here https://github.com/tealeg/xlsx/issues/739

    opened by horsley 0
  • ValueOnly option truncating break xml

    ValueOnly option truncating break xml

    Got an error, xml.Decoder.Decode: XML syntax error on line 2: element <row> closed by </c>

    a file with dimension <dimension ref="A1:I1038378"/>

    many rows with empty cells.

    I'll try to fix that

    opened by horsley 3
  • SetHyperlink execution error

    SetHyperlink execution error

    "SetHyperlink" executes an error when opening the excel file

    opened by fxrz12 0
  • v3: got empty string in some cells with content

    v3: got empty string in some cells with content

    I got a strange xlsx file from one of my clients. Content of some cells in this file cannot be accessed correctly. Instead, empty strings were returned.

    However, v1 works corretly on this file. You can remove comments to see the difference.

    Here's my testing code.

    package main
    
    import (
    	"fmt"
    	"github.com/tealeg/xlsx"
    	xlsx_v3 "github.com/tealeg/xlsx/v3"
    )
    
    func GetRowCell(m map[string]int, row *xlsx.Row, index string) string {
    	val, ok := m[index]
    	if !ok {
    		return ""
    	}
    	return row.Cells[val].Value
    }
    
    func GetRowCellV3(m map[string]int, row *xlsx_v3.Row, index string) string {
    	val, ok := m[index]
    	if !ok {
    		return ""
    	}
    	return row.GetCell(val).Value
    }
    
    func main() {
    	//file, err := xlsx.OpenFile("/path/to/issue.xlsx")
    	file, err := xlsx_v3.OpenFile("/path/to/issue.xlsx")
    
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    
    	sheet := file.Sheets[0]
    	maxRow := sheet.MaxRow
    	nameCol := map[string]int{"品牌名称": 8, "备案品名": 14}
    
    	for i := 0; i < maxRow; i++ {
    		//row := sheet.Row(i)
    		//brandName := GetRowCell(nameCol, row, "品牌名称")
    		//recordName := GetRowCell(nameCol, row, "备案品名")
    
    		row, _ := sheet.Row(i)
    		brandName := GetRowCellV3(nameCol, row, "品牌名称")
    		recordName := GetRowCellV3(nameCol, row, "备案品名")
    
    		fmt.Printf("BrandName:%v RecordName:%v\n", brandName, recordName)
    	}
    }
    

    module version

    • V1: v1.0.5
    • V3: v3.2.3

    issue file issue.xlsx

    opened by sunxia0 0
  • Time accuracy

    Time accuracy

    read "2018-04-27 19:00:00" as "2018-04-27 18:59:59"

    Repair method Add an offset value when subtracting float numbers in the TimeFromExcelTime function roundEpsilon = 1e-9 var floatPart = excelTime - float64(wholeDaysPart) + roundEpsilon

    opened by zhangshunli 0
  • Allow to add names to the workbook

    Allow to add names to the workbook

    I've added a function to allow the library user to add names to the worksheet. At the moment names are read-only.

    opened by LeonB 0
  • Can not open excel files when added AutoFilter

    Can not open excel files when added AutoFilter

    1.Version: v3.2.3 2.Test code:

    import (
    	"github.com/tealeg/xlsx/v3"
    )
    
    type structTest struct {
    	IntVal     int    `xlsx:"0"`
    	StringVal  string  `xlsx:"1"`
    	FloatVal   float64 `xlsx:"2"`
    	IgnoredVal int     `xlsx:"3"`
    	BoolVal    bool    `xlsx:"4"`
    }
    
    func main() {
    	structVal := &structTest{
    		IntVal:     16,
    		StringVal:  "hello world",
    		FloatVal:   3.14159216,
    		IgnoredVal: 7,
    		BoolVal:    true,
    	}
    
    	//create a new xlsx file and write a struct
    	file := xlsx.NewFile()
    	sheet, _ := file.AddSheet("TestSheet")
    	row := sheet.AddRow()
    	row.SetHeight(12.5)
    	row.WriteStruct(structVal, -1)
    	sheet.AutoFilter = &xlsx.AutoFilter{TopLeftCell: "A1", BottomRightCell: "E1"}
    	err := file.Save("test.xlsx")
    	if err != nil {
    		panic(err)
    	}
    }
    

    3.Open 'test.xlsx' file, have this error message image 4.This issue is similar to the https://github.com/tealeg/xlsx/issues/679

    opened by linzhicheng5512 0
  • Thousand Seperator needed

    Thousand Seperator needed

    Hello,

    I could not find Thousand Seperator feature for numeric values. Is there a plan to add this feature? Thanks.

    image

    opened by OguzhanOzturk 0
  • Error closing and returning file with email hyperlink

    Error closing and returning file with email hyperlink

    Hi guys! How are you?

    I've a question, when I try to return the file xlsx.File (converting to []bytes) and it contains the cell with a Hyperlink (email), the file breaks and it becomes impossible to open it.

    Is it possible to clear all kind of formatting, hyperlink or something like that just so I can return the file successfully?

    Image: Screen Shot 2021-07-26 at 18 58 21

    opened by thales-assis 2
Releases(v3.2.4)
  • v3.2.4(Dec 13, 2021)

  • v3.2.3(Nov 16, 2020)

    This release fixes a single issue that caused panics when writing files, derived from existing files, where one or more of the existing sheets had not been visited and thus had no currentRow set on the Sheet. See issue #644 for details.

    Source code(tar.gz)
    Source code(zip)
  • v3.2.2(Nov 14, 2020)

  • v3.2.1(Nov 10, 2020)

    There are serious known bugs in this release. We're working to resolve them and a 3.2.2 will follow as soon as possible.

    Issues resolved in this release - see v3.2.1 milestone :

    • Empty cells are filled by the first column name - v3.2.0 #594
    • High memory usage while creating a xlsx file and xlsx.UseDiskVCellStore not working #596
    • Fixes internal links #620
    • Combine cells in the same sheet and set the droplist. Excel is damaged #610

    This release was requested as people are waiting on some of the bug fixes. All outstanding bugs for the milestone have been pushed onto the v3.3.0 milestone instead.

    Source code(tar.gz)
    Source code(zip)
  • v3.2.0(Jun 20, 2020)

    This release comprises the following changes:

    • The addition of Cell.GetCoordinates() and Row.GetCoordinate() functions that fix issue #586 .
    • #581 allows the Row.WriteSlice method to accept slices as a target instead of just pointers to slices (the old behaviour is still supported).
    • #582 polishes some code a little but has no external effects.
    Source code(tar.gz)
    Source code(zip)
  • v3.1.1(Jun 9, 2020)

    Summary

    Version 3.1.1 fixes a bug that causes cell values to be blanked (or actually be zero-value structs) when reading a sheet that contains hyperlinks. See issue #574 .

    Source code(tar.gz)
    Source code(zip)
  • v3.1.0(Jun 6, 2020)

    Summary

    Version 3.1.0 fixes a number of significant issues and adds support for font strike-through, but should otherwise be 100% compatible with v3.0.0.

    Changes

    A full list of changes can be found here

    Source code(tar.gz)
    Source code(zip)
  • v3.0.0(Apr 27, 2020)

    Summary

    Version 3.0.0 of the xlsx library fixes a significant number of issues, but breaks backwards compatibility in order to do so. For a full list of changes see the milestone.

    DiskV backend

    You can now optionally pass the UseDiskVCellStore operation to all methods that open, or create an xlsx.File. Selecting this option will result in much lower memory usage when handling large sheets, but will run slightly slower than the default in-memory cell store backend.

    Streaming support removed

    If you were previously using the StreamFileBuilder you should use V2 of this library of earlier.

    Sheet.ForEachRow and Row.ForEachCell accept options.

    You can indicate that you'd like to SkipEmptyRows or SkipEmptyCells.

    Source code(tar.gz)
    Source code(zip)
  • v2.0.1(Nov 14, 2019)

  • v2.0.0(Nov 2, 2019)

    This release breaks an important, but bad, assumption that there should be a 1-to-1 mapping between the cells in a sheet and the column definitions. This model simplified the development of the original library a little, but it defeats the purpose of the col definitions (to apply stylistic information over ranges of columns).

    Numerous other fixes have been included. For a full list of changes look here: https://github.com/tealeg/xlsx/milestone/5?closed=1

    Source code(tar.gz)
    Source code(zip)
  • v1.0.5(Oct 8, 2019)

    This branch encapsulates the current state of the master branch prior to branching to the v1 branch to allow parallel maintenance fo the v1.x.x versions and the proposed v2.x.x versions.

    Source code(tar.gz)
    Source code(zip)
  • go1.1.1(Jul 12, 2019)

    I’ve been using the master branch at incredible scale, for quite some time. We have tons of unit tests on top of the library, and we have lots of users that would complain to me Immediately if this wasn’t working correctly. This branch works. Furthermore, I hope you can find someone to help you get release.

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(May 23, 2017)

    As pointed out in #306 we haven't done formal release tags since 2013. As Go's vendoring and dependency management story has now started to crystalise, it does feel like a good time to change this.

    Plenty of people are using xlsx in production, so let's formally call the current state v1.0.0.

    Source code(tar.gz)
    Source code(zip)
Owner
Geoffrey J. Teale
Developer Experience engineer at HDI Systems Cloud Competence Centre.
Geoffrey J. Teale
Dasel - Select, put and delete data from JSON, TOML, YAML, XML and CSV files with a single tool.

Select, put and delete data from JSON, TOML, YAML, XML and CSV files with a single tool. Supports conversion between formats and can be used as a Go package.

Tom Wright 1.7k Jan 6, 2022
Package for indexing zip files and storing a compressed index

zipindex zipindex provides a size optimized representation of a zip file to allow decompressing the file without reading the zip file index. It will o

High Performance, Kubernetes Native Object Storage 24 Oct 15, 2021
Generates data structure definitions from JSON files for any kind of programming language

Overview Archivist generates data structure definitions from JSON files for any kind of programming language. It also provides a library for golang to

Kingsgroup 45 Jan 2, 2022
Golang string comparison and edit distance algorithms library, featuring : Levenshtein, LCS, Hamming, Damerau levenshtein (OSA and Adjacent transpositions algorithms), Jaro-Winkler, Cosine, etc...

Go-edlib : Edit distance and string comparison library Golang string comparison and edit distance algorithms library featuring : Levenshtein, LCS, Ham

Hugo Bollon 300 Jan 11, 2022
Golang library for querying and parsing OFX

OFXGo OFXGo is a library for querying OFX servers and/or parsing the responses. It also provides an example command-line client to demonstrate the use

Aaron Lindsay 95 Jan 1, 2022
Library for hashing any Golang interface

recursive-deep-hash Library for hashing any Golang interface Making huge struct comparison fast & easy How to use package main import ( "fmt" "git

Panos Petropoulos 5 Jan 10, 2022
A radix sorting library for Go (golang)

zermelo A radix sorting library for Go. Trade memory for speed! import "github.com/shawnsmithdev/zermelo" func foo(large []uint64) zermelo.Sort(l

Shawn Smith 46 Dec 10, 2021
Go native library for fast point tracking and K-Nearest queries

Geo Index Geo Index library Overview Splits the earth surface in a grid. At each cell we can store data, such as list of points, count of points, etc.

Hailo Network IP Ltd 333 Dec 31, 2021
Data structure and algorithm library for go, designed to provide functions similar to C++ STL

GoSTL English | 简体中文 Introduction GoSTL is a data structure and algorithm library for go, designed to provide functions similar to C++ STL, but more p

stirlingx 359 Dec 30, 2021
Zero allocation Nullable structures in one library with handy conversion functions, marshallers and unmarshallers

nan - No Allocations Nevermore Package nan - Zero allocation Nullable structures in one library with handy conversion functions, marshallers and unmar

Andrey Kuzmin 46 Dec 20, 2021
A feature complete and high performance multi-group Raft library in Go.

Dragonboat - A Multi-Group Raft library in Go / 中文版 News 2021-01-20 Dragonboat v3.3 has been released, please check CHANGELOG for all changes. 2020-03

lni 4k Jan 5, 2022
Document Indexing and Searching Library in Go

Fehrist Fehrist is a pure Go library for indexing different types of documents. Currently it supports only CSV and JSON but flexible architecture give

Adnan Siddiqi 13 Nov 22, 2021
A small flexible merge library in go

conjungo A merge utility designed for flexibility and customizability. The library has a single simple point of entry that works out of the box for mo

InVision 99 Dec 17, 2021
A Go library for an efficient implementation of a skip list: https://godoc.org/github.com/MauriceGit/skiplist

Fast Skiplist Implementation This Go-library implements a very fast and efficient Skiplist that can be used as direct substitute for a balanced tree o

Maurice Tollmien 182 Dec 29, 2021
Go Library [DEPRECATED]

Tideland Go Library Description The Tideland Go Library contains a larger set of useful Google Go packages for different purposes. ATTENTION: The cell

Tideland 195 Dec 16, 2021
an R-Tree library for Go

rtreego A library for efficiently storing and querying spatial data in the Go programming language. About The R-tree is a popular data structure for e

Daniel Connelly 497 Jan 9, 2022
indexing library for Go

Bluge modern text indexing in go - blugelabs.com Features Supported field types: Text, Numeric, Date, Geo Point Supported query types: Term, Phrase, M

Bluge Labs 793 Jan 7, 2022
Go library implementing xor filters

xorfilter: Go library implementing xor filters Bloom filters are used to quickly check whether an element is part of a set. Xor filters are a faster a

null 524 Jan 8, 2022
The Go library that will drive you to AOP world!

Beyond The Golang library that will drive you to the AOP paradigm world! Check Beyond Documentation What's AOP? In computing, aspect-oriented programm

Wesovi Labs 46 Dec 15, 2021