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

Related tags

File Handling 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.

Current status

Before using this library please read this: https://github.com/tealeg/xlsx/discussions/663

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

Comments
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Fails to open with Google Docs

    Fails to open with Google Docs

    my sheet is simple and based on the Write example. I only use those 4 or 5 methods. Absolutely nothing fancy. The Sheets can be opened with Excel, however, not consistently with Google Docs. Sorry Google does not provide an explanation.

    needs more info 
    opened by rbucker 13
  • Open and Save xlsx Error

    Open and Save xlsx Error

    I use Mac Office 2013 to generator a xlsx,and Use following code to edit xlsx file and open test2.xlsx, it tell me this file need repair.

    
    func main() {
        file, err := xlsx.OpenFile("test.xlsx")
        if err != nil {
            log.Fatal(err)
        }
    
        sheet := file.Sheets[0]
        row := sheet.AddRow()
        row.AddCell().SetValue("12313131")
        err = file.Save("test2.xlsx")
        if err != nil {
            log.Fatal(err)
        }
    }
    
    
    waiting for confirmation from user 
    opened by qhsong 12
  • Add support for StreamCell merging and custom row heights

    Add support for StreamCell merging and custom row heights

    Adds support for Merge() and Height() for StreamCell/StreamRow.

    To merge a StreamCell, call Merge(h, v) with the number of extra cells to merge in each direction. Note: does not do any advanced bounds/overlap checking, just ensures that it doesn't go beyond the width of the stream sheet.

    To set a custom height, create a StreamRow and call Height(). It must be written to the sheet with WriteRowS().

    This PR also resolves a few tests that were broken on the tip of the v1 branch related to styles and date formatting.

    opened by colinmroberts 0
  • Resource leakage in the lib.go file

    Resource leakage in the lib.go file

    1、rc, err := worksheetRelsFile.Open() in the makeHyperlinkTable function does not close the RC handle. As a result, resource leakage occurs. 2、In the readSheetsFromZipFile function, rc, err = f.Open() does not close the rc handle, causing resource leakage. 3、In the readSharedStringsFromZipFile function, rc, err = f.Open() does not close the rc handle, causing resource leakage. 4、In the readStylesFromZipFile function, rc, err = f.Open() does not close the rc handle, causing resource leakage. 5、In the readThemeFromZipFile function, rc, err = f.Open() does not close the rc handle, causing resource leakage. 6、In the readWorkbookRelationsFromZipFile function, rc, err = workbookRels.Open() does not close the rc handle, causing resource leakage.

    opened by zhangyue9999 0
  • The func (f *File) Save(path string) (err error) resource in the file.go file is leaked.

    The func (f *File) Save(path string) (err error) resource in the file.go file is leaked.

    In func (f *File) Save(path string) (err error), target.Close() must be after os.Create and before f.Write. Otherwise, resource leakage may occur if f.Write(target) fails to be closed.

    opened by zhangyue9999 0
  • Security protection is recommended for functions OpenReaderAt and OpenFile.

    Security protection is recommended for functions OpenReaderAt and OpenFile.

    The functions OpenReaderAt and OpenFile are added to prevent bomb attack (limiting the total number of files). The restrictions on the number of sheets, size of a single file, and size of the total file are added to prevent security attacks caused by opening files with high compression ratios.

    opened by zhangyue9999 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
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)
  • 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)
  • 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)
Owner
Geoffrey J. Teale
Developer Experience engineer at HDI Systems Cloud Competence Centre.
Geoffrey J. Teale
A Go io/fs filesystem implementation for reading files in a Github gists.

GistFS GistFS is an io/fs implementation that enables to read files stored in a given Gist. Requirements This module depends on io/fs which is only av

Jean Hadrien Chabran 126 Oct 14, 2022
Atomic: a go package for atomic file writing

atomic import "github.com/natefinch/atomic" atomic is a go package for atomic file writing By default, writing to a file in go (and generally any lan

null 0 Nov 10, 2021
app-services-go-linter plugin analyze source tree of Go files and validates the availability of i18n strings in *.toml files

app-services-go-linter app-services-go-linter plugin analyze source tree of Go files and validates the availability of i18n strings in *.toml files. A

Red Hat Developer 2 Nov 29, 2021
Split text files into gzip files with x lines

hakgzsplit split lines of text into multiple gzip files

Luke Stephens (hakluke) 6 Jun 21, 2022
Easily create Go files from stub files

go-stubs Easily create .go files from stub files in your projects. Usage go get github.com/nwby/go-stubs Create a stub file: package stubs type {{.Mo

Sam Newby 4 Jan 27, 2022
Golang PDF library for creating and processing PDF files (pure go)

UniPDF - PDF for Go UniDoc UniPDF is a PDF library for Go (golang) with capabilities for creating and reading, processing PDF files. The library is wr

UniDoc 1.7k Dec 7, 2022
Vaala archive is a tar archive tool & library optimized for lots of small files.

?? Vaar ?? Vaala archive is a tar archive tool & library optimized for lots of small files. Written in Golang, vaar performs operations in parallel &

Qing Moy 14 Sep 12, 2022
Golang wrapper for Exiftool : extract as much metadata as possible (EXIF, ...) from files (pictures, pdf, office documents, ...)

go-exiftool go-exiftool is a golang library that wraps ExifTool. ExifTool's purpose is to extract as much metadata as possible (EXIF, IPTC, XMP, GPS,

null 148 Dec 5, 2022
Load GTFS files in golang

go-gtfs Load GTFS files in Go. The project is in maintenance mode. It is kept compatible with changes in the Go ecosystem but no new features will be

Louis 34 Dec 5, 2022
Merge some files in a path with custom extension in golang

goMerge Merge some files in a path with custom extension in golang Feature Walk in a path with a goroutine using parallelism Merge files with custom e

Javad Rajabzade 4 Apr 26, 2022
QueryCSV enables you to load CSV files and manipulate them using SQL queries then after you finish you can export the new values to a CSV file

QueryCSV enable you to load CSV files and manipulate them using SQL queries then after you finish you can export the new values to CSV file

Mohamed Shapan 100 Dec 22, 2021
🏵 Gee is tool of stdin to each files and stdout

Gee is tool of stdin to each files and stdout. It is similar to the tee command, but there are more functions for convenience. In addition, it was written as go. which provides output to stdout and files.

HAHWUL 75 Nov 17, 2022
Easily create & extract archives, and compress & decompress files of various formats

archiver Introducing Archiver 3.1 - a cross-platform, multi-format archive utility and Go library. A powerful and flexible library meets an elegant CL

Matt Holt 3.8k Nov 30, 2022
A Go filesystem package for working with files and directories

Stowage A Go filesystem package for working with files and directories, it features a simple API with support for the common files and directories ope

null 19 May 28, 2021
🌳 📂 The utility displays a tree of directories and files(symlinks in future).

dirTree The utility displays a tree of directories and files. usage: dirTree [-f] How it works with directory, where I wrote this project for example

Hutiev Alexander 2 Aug 12, 2021
Allows parsing CSV files into custom structs and implements required fields that can't be empty

Welcome to Go Custom CSV Parser ?? Allows parsing CSV files into custom structs and implements required fields that can't be empty ?? Homepage Install

Elmedin Turkeš 2 Nov 9, 2021
Utility for working with files and folders stored on Google Drive

skicka Utility for working with files and folders stored on Google Drive. Note: skicka is not an official Google product! Intro skicka makes it easy t

null 0 Nov 15, 2021
Provide an upload endpoint that stores files on pinata and returns a json response with the uploaded file pinata url

Purpose Build a template repository to get to coding as quickly as possible, by starting from a common template which follows the guidelines here Feat

Dathan Vance Pattishall 0 Dec 30, 2021