Excelize
Introduction
Excelize is a library written in pure Go providing a set of functions that allow you to write to and read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and writing spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports complex components by high compatibility, and provided streaming API for generating or reading data from a worksheet with huge amounts of data. This library needs Go version 1.16 or later. The full docs can be seen using go’s built-in documentation tool, or online at go.dev and docs reference.
Basic Usage
Installation
go get github.com/xuri/excelize
- If your packages are managed using Go Modules, please install with following command.
go get github.com/xuri/excelize/v2
Create spreadsheet
Here is a minimal example usage that will create spreadsheet file.
package main import ( "fmt" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() // Create a new sheet. index, err := f.NewSheet("Sheet2") if err != nil { fmt.Println(err) return } // Set value of a cell. f.SetCellValue("Sheet2", "A2", "Hello world.") f.SetCellValue("Sheet1", "B2", 100) // Set active sheet of the workbook. f.SetActiveSheet(index) // Save spreadsheet by the given path. if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
Reading spreadsheet
The following constitutes the bare to read a spreadsheet document.
package main import ( "fmt" "github.com/xuri/excelize/v2" ) func main() { f, err := excelize.OpenFile("Book1.xlsx") if err != nil { fmt.Println(err) return } defer func() { // Close the spreadsheet. if err := f.Close(); err != nil { fmt.Println(err) } }() // Get value from cell by given worksheet name and cell reference. cell, err := f.GetCellValue("Sheet1", "B2") if err != nil { fmt.Println(err) return } fmt.Println(cell) // Get all the rows in the Sheet1. rows, err := f.GetRows("Sheet1") if err != nil { fmt.Println(err) return } for _, row := range rows { for _, colCell := range row { fmt.Print(colCell, "t") } fmt.Println() } }
Add chart to spreadsheet file
With Excelize chart generation and management is as easy as a few lines of code. You can build charts based on data in your worksheet or generate charts without any data in your worksheet at all.
package main import ( "fmt" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() for idx, row := range [][]interface{}{ {nil, "Apple", "Orange", "Pear"}, {"Small", 2, 3, 3}, {"Normal", 5, 2, 4}, {"Large", 6, 7, 8}, } { cell, err := excelize.CoordinatesToCellName(1, idx+1) if err != nil { fmt.Println(err) return } f.SetSheetRow("Sheet1", cell, &row) } if err := f.AddChart("Sheet1", "E1", &excelize.Chart{ Type: excelize.Col3DClustered, Series: []excelize.ChartSeries{ { Name: "Sheet1!$A$2", Categories: "Sheet1!$B$1:$D$1", Values: "Sheet1!$B$2:$D$2", }, { Name: "Sheet1!$A$3", Categories: "Sheet1!$B$1:$D$1", Values: "Sheet1!$B$3:$D$3", }, { Name: "Sheet1!$A$4", Categories: "Sheet1!$B$1:$D$1", Values: "Sheet1!$B$4:$D$4", }}, Title: excelize.ChartTitle{ Name: "Fruit 3D Clustered Column Chart", }, }); err != nil { fmt.Println(err) return } // Save spreadsheet by the given path. if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
Add picture to spreadsheet file
package main import ( "fmt" _ "image/gif" _ "image/jpeg" _ "image/png" "github.com/xuri/excelize/v2" ) func main() { f, err := excelize.OpenFile("Book1.xlsx") if err != nil { fmt.Println(err) return } defer func() { // Close the spreadsheet. if err := f.Close(); err != nil { fmt.Println(err) } }() // Insert a picture. if err := f.AddPicture("Sheet1", "A2", "image.png", nil); err != nil { fmt.Println(err) } // Insert a picture to worksheet with scaling. if err := f.AddPicture("Sheet1", "D2", "image.jpg", &excelize.GraphicOptions{ScaleX: 0.5, ScaleY: 0.5}); err != nil { fmt.Println(err) } // Insert a picture offset in the cell with printing support. enable, disable := true, false if err := f.AddPicture("Sheet1", "H2", "image.gif", &excelize.GraphicOptions{ PrintObject: &enable, LockAspectRatio: false, OffsetX: 15, OffsetY: 10, Locked: &disable, }); err != nil { fmt.Println(err) } // Save the spreadsheet with the origin path. if err = f.Save(); err != nil { fmt.Println(err) } }
Contributing
Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change. XML is compliant with part 1 of the 5th edition of the ECMA-376 Standard for Office Open XML.
Licenses
This program is under the terms of the BSD 3-Clause License. See https://opensource.org/licenses/BSD-3-Clause.
The Excel logo is a trademark of Microsoft Corporation. This artwork is an adaptation.
gopher.{ai,svg,png} was created by Takuya Ueda. Licensed under the Creative Commons 3.0 Attributions license.
Package excelize providing a set of functions that allow you to write to and
read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and
writing spreadsheet documents generated by Microsoft Excel™ 2007 and later.
Supports complex components by high compatibility, and provided streaming
API for generating or reading data from a worksheet with huge amounts of
data. This library needs Go version 1.16 or later.
See https://xuri.me/excelize for more information about this package.
- Constants
- Variables
- func CellNameToCoordinates(cell string) (int, int, error)
- func ColumnNameToNumber(name string) (int, error)
- func ColumnNumberToName(num int) (string, error)
- func CoordinatesToCellName(col, row int, abs …bool) (string, error)
- func Decrypt(raw []byte, opts *Options) (packageBuf []byte, err error)
- func Encrypt(raw []byte, opts *Options) ([]byte, error)
- func ExcelDateToTime(excelDate float64, use1904Format bool) (time.Time, error)
- func HSLToRGB(h, s, l float64) (r, g, b uint8)
- func JoinCellName(col string, row int) (string, error)
- func RGBToHSL(r, g, b uint8) (h, s, l float64)
- func SplitCellName(cell string) (string, int, error)
- func ThemeColor(baseColor string, tint float64) string
- type Alignment
- type AppProperties
- type ArgType
- type AutoFilterOptions
- type Border
- type Cell
- type CellType
- type Chart
- type ChartAxis
- type ChartDimension
- type ChartLegend
- type ChartLine
- type ChartMarker
- type ChartNumFmt
- type ChartPlotArea
- type ChartSeries
- type ChartTitle
- type ChartType
- type ColorMappingType
- type Cols
-
- func (cols *Cols) Error() error
- func (cols *Cols) Next() bool
- func (cols *Cols) Rows(opts …Options) ([]string, error)
- type Comment
- type ConditionalFormatOptions
- type DataIntegrity
- type DataValidation
-
- func NewDataValidation(allowBlank bool) *DataValidation
-
- func (dv *DataValidation) SetDropList(keys []string) error
- func (dv *DataValidation) SetError(style DataValidationErrorStyle, title, msg string)
- func (dv *DataValidation) SetInput(title, msg string)
- func (dv *DataValidation) SetRange(f1, f2 interface{}, t DataValidationType, o DataValidationOperator) error
- func (dv *DataValidation) SetSqref(sqref string)
- func (dv *DataValidation) SetSqrefDropList(sqref string)
- type DataValidationErrorStyle
- type DataValidationOperator
- type DataValidationType
- type DefinedName
- type DocProperties
- type EncryptedKey
- type Encryption
- type ErrSheetNotExist
-
- func (err ErrSheetNotExist) Error() string
- type File
-
- func NewFile() *File
- func OpenFile(filename string, opts …Options) (*File, error)
- func OpenReader(r io.Reader, opts …Options) (*File, error)
-
- func (f *File) AddChart(sheet, cell string, chart *Chart, combo …*Chart) error
- func (f *File) AddChartSheet(sheet string, chart *Chart, combo …*Chart) error
- func (f *File) AddComment(sheet string, comment Comment) error
- func (f *File) AddDataValidation(sheet string, dv *DataValidation) error
- func (f *File) AddPicture(sheet, cell, name string, opts *GraphicOptions) error
- func (f *File) AddPictureFromBytes(sheet, cell string, pic *Picture) error
- func (f *File) AddPivotTable(opts *PivotTableOptions) error
- func (f *File) AddShape(sheet, cell string, opts *Shape) error
- func (f *File) AddSparkline(sheet string, opts *SparklineOptions) error
- func (f *File) AddTable(sheet string, table *Table) error
- func (f *File) AddVBAProject(file []byte) error
- func (f *File) AutoFilter(sheet, rangeRef string, opts []AutoFilterOptions) error
- func (f *File) CalcCellValue(sheet, cell string, opts …Options) (result string, err error)
- func (f *File) CharsetTranscoder(fn charsetTranscoderFn) *File
- func (f *File) Close() error
- func (f *File) Cols(sheet string) (*Cols, error)
- func (f *File) CopySheet(from, to int) error
- func (f *File) DeleteChart(sheet, cell string) error
- func (f *File) DeleteComment(sheet, cell string) error
- func (f *File) DeleteDataValidation(sheet string, sqref …string) error
- func (f *File) DeleteDefinedName(definedName *DefinedName) error
- func (f *File) DeletePicture(sheet, cell string) error
- func (f *File) DeleteSheet(sheet string) error
- func (f *File) DuplicateRow(sheet string, row int) error
- func (f *File) DuplicateRowTo(sheet string, row, row2 int) error
- func (f *File) GetActiveSheetIndex() (index int)
- func (f *File) GetAppProps() (ret *AppProperties, err error)
- func (f *File) GetCellFormula(sheet, cell string) (string, error)
- func (f *File) GetCellHyperLink(sheet, cell string) (bool, string, error)
- func (f *File) GetCellRichText(sheet, cell string) (runs []RichTextRun, err error)
- func (f *File) GetCellStyle(sheet, cell string) (int, error)
- func (f *File) GetCellType(sheet, cell string) (CellType, error)
- func (f *File) GetCellValue(sheet, cell string, opts …Options) (string, error)
- func (f *File) GetColOutlineLevel(sheet, col string) (uint8, error)
- func (f *File) GetColStyle(sheet, col string) (int, error)
- func (f *File) GetColVisible(sheet, col string) (bool, error)
- func (f *File) GetColWidth(sheet, col string) (float64, error)
- func (f *File) GetCols(sheet string, opts …Options) ([][]string, error)
- func (f *File) GetComments(sheet string) ([]Comment, error)
- func (f *File) GetConditionalFormats(sheet string) (map[string][]ConditionalFormatOptions, error)
- func (f *File) GetDataValidations(sheet string) ([]*DataValidation, error)
- func (f *File) GetDefaultFont() (string, error)
- func (f *File) GetDefinedName() []DefinedName
- func (f *File) GetDocProps() (ret *DocProperties, err error)
- func (f *File) GetMergeCells(sheet string) ([]MergeCell, error)
- func (f *File) GetPageLayout(sheet string) (PageLayoutOptions, error)
- func (f *File) GetPageMargins(sheet string) (PageLayoutMarginsOptions, error)
- func (f *File) GetPictures(sheet, cell string) ([]Picture, error)
- func (f *File) GetRowHeight(sheet string, row int) (float64, error)
- func (f *File) GetRowOutlineLevel(sheet string, row int) (uint8, error)
- func (f *File) GetRowVisible(sheet string, row int) (bool, error)
- func (f *File) GetRows(sheet string, opts …Options) ([][]string, error)
- func (f *File) GetSheetDimension(sheet string) (string, error)
- func (f *File) GetSheetIndex(sheet string) (int, error)
- func (f *File) GetSheetList() (list []string)
- func (f *File) GetSheetMap() map[int]string
- func (f *File) GetSheetName(index int) (name string)
- func (f *File) GetSheetProps(sheet string) (SheetPropsOptions, error)
- func (f *File) GetSheetView(sheet string, viewIndex int) (ViewOptions, error)
- func (f *File) GetSheetVisible(sheet string) (bool, error)
- func (f *File) GetWorkbookProps() (WorkbookPropsOptions, error)
- func (f *File) GroupSheets(sheets []string) error
- func (f *File) InsertCols(sheet, col string, n int) error
- func (f *File) InsertPageBreak(sheet, cell string) error
- func (f *File) InsertRows(sheet string, row, n int) error
- func (f *File) MergeCell(sheet, hCell, vCell string) error
- func (f *File) NewConditionalStyle(style *Style) (int, error)
- func (f *File) NewSheet(sheet string) (int, error)
- func (f *File) NewStreamWriter(sheet string) (*StreamWriter, error)
- func (f *File) NewStyle(style *Style) (int, error)
- func (f *File) ProtectSheet(sheet string, opts *SheetProtectionOptions) error
- func (f *File) ProtectWorkbook(opts *WorkbookProtectionOptions) error
- func (f *File) ReadZipReader(r *zip.Reader) (map[string][]byte, int, error)
- func (f *File) RemoveCol(sheet, col string) error
- func (f *File) RemovePageBreak(sheet, cell string) error
- func (f *File) RemoveRow(sheet string, row int) error
- func (f *File) Rows(sheet string) (*Rows, error)
- func (f *File) Save(opts …Options) error
- func (f *File) SaveAs(name string, opts …Options) error
- func (f *File) SearchSheet(sheet, value string, reg …bool) ([]string, error)
- func (f *File) SetActiveSheet(index int)
- func (f *File) SetAppProps(appProperties *AppProperties) error
- func (f *File) SetCellBool(sheet, cell string, value bool) error
- func (f *File) SetCellDefault(sheet, cell, value string) error
- func (f *File) SetCellFloat(sheet, cell string, value float64, precision, bitSize int) error
- func (f *File) SetCellFormula(sheet, cell, formula string, opts …FormulaOpts) error
- func (f *File) SetCellHyperLink(sheet, cell, link, linkType string, opts …HyperlinkOpts) error
- func (f *File) SetCellInt(sheet, cell string, value int) error
- func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error
- func (f *File) SetCellStr(sheet, cell, value string) error
- func (f *File) SetCellStyle(sheet, hCell, vCell string, styleID int) error
- func (f *File) SetCellValue(sheet, cell string, value interface{}) error
- func (f *File) SetColOutlineLevel(sheet, col string, level uint8) error
- func (f *File) SetColStyle(sheet, columns string, styleID int) error
- func (f *File) SetColVisible(sheet, columns string, visible bool) error
- func (f *File) SetColWidth(sheet, startCol, endCol string, width float64) error
- func (f *File) SetConditionalFormat(sheet, rangeRef string, opts []ConditionalFormatOptions) error
- func (f *File) SetDefaultFont(fontName string) error
- func (f *File) SetDefinedName(definedName *DefinedName) error
- func (f *File) SetDocProps(docProperties *DocProperties) error
- func (f *File) SetHeaderFooter(sheet string, opts *HeaderFooterOptions) error
- func (f *File) SetPageLayout(sheet string, opts *PageLayoutOptions) error
- func (f *File) SetPageMargins(sheet string, opts *PageLayoutMarginsOptions) error
- func (f *File) SetPanes(sheet string, panes *Panes) error
- func (f *File) SetRowHeight(sheet string, row int, height float64) error
- func (f *File) SetRowOutlineLevel(sheet string, row int, level uint8) error
- func (f *File) SetRowStyle(sheet string, start, end, styleID int) error
- func (f *File) SetRowVisible(sheet string, row int, visible bool) error
- func (f *File) SetSheetBackground(sheet, picture string) error
- func (f *File) SetSheetBackgroundFromBytes(sheet, extension string, picture []byte) error
- func (f *File) SetSheetCol(sheet, cell string, slice interface{}) error
- func (f *File) SetSheetDimension(sheet string, rangeRef string) error
- func (f *File) SetSheetName(source, target string) error
- func (f *File) SetSheetProps(sheet string, opts *SheetPropsOptions) error
- func (f *File) SetSheetRow(sheet, cell string, slice interface{}) error
- func (f *File) SetSheetView(sheet string, viewIndex int, opts *ViewOptions) error
- func (f *File) SetSheetVisible(sheet string, visible bool, veryHidden …bool) error
- func (f *File) SetWorkbookProps(opts *WorkbookPropsOptions) error
- func (f *File) UngroupSheets() error
- func (f *File) UnmergeCell(sheet, hCell, vCell string) error
- func (f *File) UnprotectSheet(sheet string, password …string) error
- func (f *File) UnprotectWorkbook(password …string) error
- func (f *File) UnsetConditionalFormat(sheet, rangeRef string) error
- func (f *File) UpdateLinkedValue() error
- func (f *File) Write(w io.Writer, opts …Options) error
- func (f *File) WriteTo(w io.Writer, opts …Options) (int64, error)
- func (f *File) WriteToBuffer() (*bytes.Buffer, error)
- type Fill
- type Font
- type FormulaOpts
- type GraphicOptions
- type HSL
-
- func (c HSL) RGBA() (uint32, uint32, uint32, uint32)
- type HeaderFooterOptions
- type HyperlinkOpts
- type KeyData
- type KeyEncryptor
- type KeyEncryptors
- type MergeCell
-
- func (m *MergeCell) GetCellValue() string
- func (m *MergeCell) GetEndAxis() string
- func (m *MergeCell) GetStartAxis() string
- type Options
- type PageLayoutMarginsOptions
- type PageLayoutOptions
- type PaneOptions
- type Panes
- type Picture
- type PivotTableField
- type PivotTableOptions
- type Protection
- type RichTextRun
- type RowOpts
- type Rows
-
- func (rows *Rows) Close() error
- func (rows *Rows) Columns(opts …Options) ([]string, error)
- func (rows *Rows) Error() error
- func (rows *Rows) GetRowOpts() RowOpts
- func (rows *Rows) Next() bool
- type Shape
- type ShapeColor
- type ShapeLine
- type SheetPropsOptions
- type SheetProtectionOptions
- type SparklineOptions
- type Stack
-
- func NewStack() *Stack
-
- func (stack *Stack) Empty() bool
- func (stack *Stack) Len() int
- func (stack *Stack) Peek() interface{}
- func (stack *Stack) Pop() interface{}
- func (stack *Stack) Push(value interface{})
- type StandardEncryptionHeader
- type StandardEncryptionVerifier
- type StreamWriter
-
- func (sw *StreamWriter) AddTable(table *Table) error
- func (sw *StreamWriter) Flush() error
- func (sw *StreamWriter) InsertPageBreak(cell string) error
- func (sw *StreamWriter) MergeCell(hCell, vCell string) error
- func (sw *StreamWriter) SetColWidth(min, max int, width float64) error
- func (sw *StreamWriter) SetPanes(panes *Panes) error
- func (sw *StreamWriter) SetRow(cell string, values []interface{}, opts …RowOpts) error
- type Style
- type Table
- type ViewOptions
- type WorkbookPropsOptions
- type WorkbookProtectionOptions
- File.SetCellFloat
View Source
const ( STCellFormulaTypeArray = "array" STCellFormulaTypeDataTable = "dataTable" STCellFormulaTypeNormal = "normal" STCellFormulaTypeShared = "shared" )
View Source
const ( DataValidationTypeCustom DataValidationTypeDate DataValidationTypeDecimal DataValidationTypeTextLength DataValidationTypeTime DataValidationTypeWhole )
Data validation types.
View Source
const ( DataValidationOperatorBetween DataValidationOperatorEqual DataValidationOperatorGreaterThan DataValidationOperatorGreaterThanOrEqual DataValidationOperatorLessThan DataValidationOperatorLessThanOrEqual DataValidationOperatorNotBetween DataValidationOperatorNotEqual )
Data validation operators.
View Source
const ( ContentTypeAddinMacro = "application/vnd.ms-excel.addin.macroEnabled.main+xml" ContentTypeDrawing = "application/vnd.openxmlformats-officedocument.drawing+xml" ContentTypeDrawingML = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml" ContentTypeMacro = "application/vnd.ms-excel.sheet.macroEnabled.main+xml" ContentTypeSheetML = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" ContentTypeSpreadSheetMLChartsheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml" ContentTypeSpreadSheetMLComments = "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml" ContentTypeSpreadSheetMLPivotCacheDefinition = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml" ContentTypeSpreadSheetMLPivotTable = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml" ContentTypeSpreadSheetMLSharedStrings = "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml" ContentTypeSpreadSheetMLTable = "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml" ContentTypeSpreadSheetMLWorksheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" ContentTypeTemplate = "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml" ContentTypeTemplateMacro = "application/vnd.ms-excel.template.macroEnabled.main+xml" ContentTypeVBA = "application/vnd.ms-office.vbaProject" ContentTypeVML = "application/vnd.openxmlformats-officedocument.vmlDrawing" NameSpaceDrawingMLMain = "http://schemas.openxmlformats.org/drawingml/2006/main" NameSpaceDublinCore = "http://purl.org/dc/elements/1.1/" NameSpaceDublinCoreMetadataInitiative = "http://purl.org/dc/dcmitype/" NameSpaceDublinCoreTerms = "http://purl.org/dc/terms/" NameSpaceExtendedProperties = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" NameSpaceXML = "http://www.w3.org/XML/1998/namespace" NameSpaceXMLSchemaInstance = "http://www.w3.org/2001/XMLSchema-instance" SourceRelationshipChart = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" SourceRelationshipChartsheet = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" SourceRelationshipDialogsheet = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet" SourceRelationshipDrawingML = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" SourceRelationshipDrawingVML = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing" SourceRelationshipExtendProperties = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" SourceRelationshipHyperLink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" SourceRelationshipImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" SourceRelationshipOfficeDocument = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" SourceRelationshipPivotCache = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition" SourceRelationshipPivotTable = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable" SourceRelationshipSharedStrings = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" SourceRelationshipTable = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/table" SourceRelationshipVBAProject = "http://schemas.microsoft.com/office/2006/relationships/vbaProject" SourceRelationshipWorkSheet = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" StrictNameSpaceDocumentPropertiesVariantTypes = "http://purl.oclc.org/ooxml/officeDocument/docPropsVTypes" StrictNameSpaceDrawingMLMain = "http://purl.oclc.org/ooxml/drawingml/main" StrictNameSpaceExtendedProperties = "http://purl.oclc.org/ooxml/officeDocument/extendedProperties" StrictNameSpaceSpreadSheet = "http://purl.oclc.org/ooxml/spreadsheetml/main" StrictSourceRelationship = "http://purl.oclc.org/ooxml/officeDocument/relationships" StrictSourceRelationshipChart = "http://purl.oclc.org/ooxml/officeDocument/relationships/chart" StrictSourceRelationshipExtendProperties = "http://purl.oclc.org/ooxml/officeDocument/relationships/extendedProperties" StrictSourceRelationshipImage = "http://purl.oclc.org/ooxml/officeDocument/relationships/image" StrictSourceRelationshipOfficeDocument = "http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument" ExtURIConditionalFormattingRuleID = "{B025F937-C7B1-47D3-B67F-A62EFF666E3E}" ExtURIConditionalFormattings = "{78C0D931-6437-407d-A8EE-F0AAD7539E65}" ExtURIDataValidations = "{CCE6A557-97BC-4B89-ADB6-D9C93CAAB3DF}" ExtURIDrawingBlip = "{28A0092B-C50C-407E-A947-70E740481C1C}" ExtURIIgnoredErrors = "{01252117-D84E-4E92-8308-4BE1C098FCBB}" ExtURIMacExcelMX = "{64002731-A6B0-56B0-2670-7721B7C09600}" ExtURIProtectedRanges = "{FC87AEE6-9EDD-4A0A-B7FB-166176984837}" ExtURISlicerCachesListX14 = "{BBE1A952-AA13-448e-AADC-164F8A28A991}" ExtURISlicerListX14 = "{A8765BA9-456A-4DAB-B4F3-ACF838C121DE}" ExtURISlicerListX15 = "{3A4CF648-6AED-40f4-86FF-DC5316D8AED3}" ExtURISparklineGroups = "{05C60535-1F16-4fd2-B633-F4F36F0B64E0}" ExtURISVG = "{96DAC541-7B7A-43D3-8B79-37D633B846F1}" ExtURITimelineRefs = "{7E03D99C-DC04-49d9-9315-930204A7B6E9}" ExtURIWebExtensions = "{F7C9EE02-42E1-4005-9D12-6889AFFD525C}" )
Source relationship and namespace.
View Source
const ( MaxCellStyles = 65430 MaxColumns = 16384 MaxColumnWidth = 255 MaxFieldLength = 255 MaxFilePathLength = 207 MaxFontFamilyLength = 31 MaxFontSize = 409 MaxRowHeight = 409 MaxSheetNameLength = 31 MinColumns = 1 MinFontSize = 1 StreamChunkSize = 1 << 24 TotalCellChars = 32767 TotalRows = 1048576 TotalSheetHyperlinks = 65529 UnzipSizeLimit = 1000 << 24 )
Excel specifications and limits
View Source
const ( ColorMappingTypeLight1 ColorMappingType = iota ColorMappingTypeDark1 ColorMappingTypeLight2 ColorMappingTypeDark2 ColorMappingTypeAccent1 ColorMappingTypeAccent2 ColorMappingTypeAccent3 ColorMappingTypeAccent4 ColorMappingTypeAccent5 ColorMappingTypeAccent6 ColorMappingTypeHyperlink ColorMappingTypeFollowedHyperlink ColorMappingTypeUnset int = -1 )
Color transformation types enumeration.
Define the default cell size and EMU unit of measurement.
View Source
var ( ErrStreamSetColWidth = errors.New("must call the SetColWidth function before the SetRow function") ErrStreamSetPanes = errors.New("must call the SetPanes function before the SetRow function") ErrColumnNumber = fmt.Errorf(`the column number must be greater than or equal to %d and less than or equal to %d`, MinColumns, MaxColumns) ErrColumnWidth = fmt.Errorf("the width of the column must be less than or equal to %d characters", MaxColumnWidth) ErrOutlineLevel = errors.New("invalid outline level") ErrCoordinates = errors.New("coordinates length must be 4") ErrExistsSheet = errors.New("the same name sheet already exists") ErrTotalSheetHyperlinks = errors.New("over maximum limit hyperlinks in a worksheet") ErrInvalidFormula = errors.New("formula not valid") ErrAddVBAProject = errors.New("unsupported VBA project") ErrMaxRows = errors.New("row number exceeds maximum limit") ErrMaxRowHeight = fmt.Errorf("the height of the row must be less than or equal to %d points", MaxRowHeight) ErrImgExt = errors.New("unsupported image extension") ErrWorkbookFileFormat = errors.New("unsupported workbook file format") ErrMaxFilePathLength = errors.New("file path length exceeds maximum limit") ErrUnknownEncryptMechanism = errors.New("unknown encryption mechanism") ErrUnsupportedEncryptMechanism = errors.New("unsupported encryption mechanism") ErrUnsupportedHashAlgorithm = errors.New("unsupported hash algorithm") ErrUnsupportedNumberFormat = errors.New("unsupported number format token") ErrPasswordLengthInvalid = errors.New("password length invalid") ErrParameterRequired = errors.New("parameter is required") ErrParameterInvalid = errors.New("parameter is invalid") ErrDefinedNameScope = errors.New("no defined name on the scope") ErrDefinedNameDuplicate = errors.New("the same name already exists on the scope") ErrCustomNumFmt = errors.New("custom number format can not be empty") ErrFontLength = fmt.Errorf("the length of the font family name must be less than or equal to %d", MaxFontFamilyLength) ErrFontSize = fmt.Errorf("font size must be between %d and %d points", MinFontSize, MaxFontSize) ErrSheetIdx = errors.New("invalid worksheet index") ErrUnprotectSheet = errors.New("worksheet has set no protect") ErrUnprotectSheetPassword = errors.New("worksheet protect password not match") ErrGroupSheets = errors.New("group worksheet must contain an active worksheet") ErrDataValidationFormulaLength = fmt.Errorf("data validation must be 0-%d characters", MaxFieldLength) ErrDataValidationRange = errors.New("data validation range exceeds limit") ErrCellCharsLength = fmt.Errorf("cell value must be 0-%d characters", TotalCellChars) ErrOptionsUnzipSizeLimit = errors.New("the value of UnzipSizeLimit should be greater than or equal to UnzipXMLSizeLimit") ErrSave = errors.New("no path defined for file, consider File.WriteTo or File.Write") ErrAttrValBool = errors.New("unexpected child of attrValBool") ErrSparklineType = errors.New("parameter 'Type' must be 'line', 'column' or 'win_loss'") ErrSparklineLocation = errors.New("parameter 'Location' is required") ErrSparklineRange = errors.New("parameter 'Range' is required") ErrSparkline = errors.New("must have the same number of 'Location' and 'Range' parameters") ErrSparklineStyle = errors.New("parameter 'Style' must between 0-35") ErrWorkbookPassword = errors.New("the supplied open workbook password is not correct") ErrSheetNameInvalid = errors.New("the sheet can not contain any of the characters :\/?*[or]") ErrSheetNameSingleQuote = errors.New("the first or last character of the sheet name can not be a single quote") ErrSheetNameBlank = errors.New("the sheet name can not be blank") ErrSheetNameLength = fmt.Errorf("the sheet name length exceeds the %d characters limit", MaxSheetNameLength) ErrTableNameLength = fmt.Errorf("the table name length exceeds the %d characters limit", MaxFieldLength) ErrCellStyles = fmt.Errorf("the cell styles exceeds the %d limit", MaxCellStyles) ErrUnprotectWorkbook = errors.New("workbook has set no protect") ErrUnprotectWorkbookPassword = errors.New("workbook protect password not match") )
View Source
var ( NameSpaceDocumentPropertiesVariantTypes = xml.Attr{Name: xml.Name{Local: "vt", Space: "xmlns"}, Value: "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"} NameSpaceDrawing2016SVG = xml.Attr{Name: xml.Name{Local: "asvg", Space: "xmlns"}, Value: "http://schemas.microsoft.com/office/drawing/2016/SVG/main"} NameSpaceDrawingML = xml.Attr{Name: xml.Name{Local: "a", Space: "xmlns"}, Value: "http://schemas.openxmlformats.org/drawingml/2006/main"} NameSpaceDrawingMLChart = xml.Attr{Name: xml.Name{Local: "c", Space: "xmlns"}, Value: "http://schemas.openxmlformats.org/drawingml/2006/chart"} NameSpaceDrawingMLSpreadSheet = xml.Attr{Name: xml.Name{Local: "xdr", Space: "xmlns"}, Value: "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"} NameSpaceMacExcel2008Main = xml.Attr{Name: xml.Name{Local: "mx", Space: "xmlns"}, Value: "http://schemas.microsoft.com/office/mac/excel/2008/main"} NameSpaceSpreadSheet = xml.Attr{Name: xml.Name{Local: "xmlns"}, Value: "http://schemas.openxmlformats.org/spreadsheetml/2006/main"} NameSpaceSpreadSheetExcel2006Main = xml.Attr{Name: xml.Name{Local: "xne", Space: "xmlns"}, Value: "http://schemas.microsoft.com/office/excel/2006/main"} NameSpaceSpreadSheetX14 = xml.Attr{Name: xml.Name{Local: "x14", Space: "xmlns"}, Value: "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"} NameSpaceSpreadSheetX15 = xml.Attr{Name: xml.Name{Local: "x15", Space: "xmlns"}, Value: "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"} SourceRelationship = xml.Attr{Name: xml.Name{Local: "r", Space: "xmlns"}, Value: "http://schemas.openxmlformats.org/officeDocument/2006/relationships"} SourceRelationshipChart20070802 = xml.Attr{Name: xml.Name{Local: "c14", Space: "xmlns"}, Value: "http://schemas.microsoft.com/office/drawing/2007/8/2/chart"} SourceRelationshipChart2014 = xml.Attr{Name: xml.Name{Local: "c16", Space: "xmlns"}, Value: "http://schemas.microsoft.com/office/drawing/2014/chart"} SourceRelationshipChart201506 = xml.Attr{Name: xml.Name{Local: "c16r2", Space: "xmlns"}, Value: "http://schemas.microsoft.com/office/drawing/2015/06/chart"} SourceRelationshipCompatibility = xml.Attr{Name: xml.Name{Local: "mc", Space: "xmlns"}, Value: "http://schemas.openxmlformats.org/markup-compatibility/2006"} )
Source relationship and namespace list, associated prefixes and schema in which it was
introduced.
HSLModel converts any color.Color to a HSL color.
View Source
var IndexedColorMapping = []string{
"000000", "FFFFFF", "FF0000", "00FF00", "0000FF", "FFFF00", "FF00FF", "00FFFF",
"000000", "FFFFFF", "FF0000", "00FF00", "0000FF", "FFFF00", "FF00FF", "00FFFF",
"800000", "008000", "000080", "808000", "800080", "008080", "C0C0C0", "808080",
"9999FF", "993366", "FFFFCC", "CCFFFF", "660066", "FF8080", "0066CC", "CCCCFF",
"000080", "FF00FF", "FFFF00", "00FFFF", "800080", "800000", "008080", "0000FF",
"00CCFF", "CCFFFF", "CCFFCC", "FFFF99", "99CCFF", "FF99CC", "CC99FF", "FFCC99",
"3366FF", "33CCCC", "99CC00", "FFCC00", "FF9900", "FF6600", "666699", "969696",
"003366", "339966", "003300", "333300", "993300", "993366", "333399", "333333",
"000000", "FFFFFF",
}
IndexedColorMapping is the table of default mappings from indexed color value
to RGB value. Note that 0-7 are redundant of 8-15 to preserve backwards
compatibility. A legacy indexing scheme for colors that is still required
for some records, and for backwards compatibility with legacy formats. This
element contains a sequence of RGB color values that correspond to color
indexes (zero-based). When using the default indexed color palette, the
values are not written out, but instead are implied. When the color palette
has been modified from default, then the entire color palette is written
out.
CellNameToCoordinates converts alphanumeric cell name to [X, Y] coordinates
or returns an error.
Example:
excelize.CellNameToCoordinates("A1") // returns 1, 1, nil excelize.CellNameToCoordinates("Z3") // returns 26, 3, nil
func ColumnNameToNumber ¶
ColumnNameToNumber provides a function to convert Excel sheet column name
(case-insensitive) to int. The function returns an error if column name
incorrect.
Example:
excelize.ColumnNameToNumber("AK") // returns 37, nil
func ColumnNumberToName ¶
ColumnNumberToName provides a function to convert the integer to Excel
sheet column title.
Example:
excelize.ColumnNumberToName(37) // returns "AK", nil
CoordinatesToCellName converts [X, Y] coordinates to alpha-numeric cell
name or returns an error.
Example:
excelize.CoordinatesToCellName(1, 1) // returns "A1", nil excelize.CoordinatesToCellName(1, 1, true) // returns "$A$1", nil
Decrypt API decrypts the CFB file format with ECMA-376 agile encryption and
standard encryption. Support cryptographic algorithm: MD4, MD5, RIPEMD-160,
SHA1, SHA256, SHA384 and SHA512 currently.
Encrypt API encrypt data with the password.
ExcelDateToTime converts a float-based excel date representation to a time.Time.
HSLToRGB converts an HSL triple to a RGB triple.
JoinCellName joins cell name from column name and row number.
RGBToHSL converts an RGB triple to a HSL triple.
SplitCellName splits cell name to column name and row number.
Example:
excelize.SplitCellName("AK74") // return "AK", 74, nil
ThemeColor applied the color with tint value.
Alignment directly maps the alignment settings of the cells.
AppProperties directly maps the document application properties.
ArgType is the type of formula argument type.
const ( ArgUnknown ArgType = iota ArgNumber ArgString ArgList ArgMatrix ArgError ArgEmpty )
Formula argument types enumeration.
type AutoFilterOptions struct { Column string Expression string }
AutoFilterOptions directly maps the auto filter settings.
Border directly maps the border settings of the cells.
type Cell struct { StyleID int Formula string Value interface{} }
Cell can be used directly in StreamWriter.SetRow to specify a style and
a value.
CellType is the type of cell value type.
const ( CellTypeUnset CellType = iota CellTypeBool CellTypeDate CellTypeError CellTypeFormula CellTypeInlineString CellTypeNumber CellTypeSharedString )
Cell value types enumeration.
type Chart struct { Type ChartType Series []ChartSeries Format GraphicOptions Dimension ChartDimension Legend ChartLegend Title ChartTitle VaryColors *bool XAxis ChartAxis YAxis ChartAxis PlotArea ChartPlotArea ShowBlanksAs string HoleSize int }
Chart directly maps the format settings of the chart.
ChartAxis directly maps the format settings of the chart axis.
type ChartDimension struct { Width uint Height uint }
ChartDimension directly maps the dimension of the chart.
type ChartLegend struct { Position string ShowLegendKey bool }
ChartLegend directly maps the format settings of the chart legend.
ChartLine directly maps the format settings of the chart line.
type ChartMarker struct { Symbol string Size int }
ChartMarker directly maps the format settings of the chart marker.
type ChartNumFmt struct { CustomNumFmt string SourceLinked bool }
ChartNumFmt directly maps the number format settings of the chart.
type ChartPlotArea struct { SecondPlotValues int ShowBubbleSize bool ShowCatName bool ShowLeaderLines bool ShowPercent bool ShowSerName bool ShowVal bool NumFmt ChartNumFmt }
ChartPlotArea directly maps the format settings of the plot area.
ChartSeries directly maps the format settings of the chart series.
type ChartTitle struct {
Name string
}
ChartTitle directly maps the format settings of the chart title.
ChartType is the type of supported chart types.
const ( Area ChartType = iota AreaStacked AreaPercentStacked Area3D Area3DStacked Area3DPercentStacked Bar BarStacked BarPercentStacked Bar3DClustered Bar3DStacked Bar3DPercentStacked Bar3DConeClustered Bar3DConeStacked Bar3DConePercentStacked Bar3DPyramidClustered Bar3DPyramidStacked Bar3DPyramidPercentStacked Bar3DCylinderClustered Bar3DCylinderStacked Bar3DCylinderPercentStacked Col ColStacked ColPercentStacked Col3D Col3DClustered Col3DStacked Col3DPercentStacked Col3DCone Col3DConeClustered Col3DConeStacked Col3DConePercentStacked Col3DPyramid Col3DPyramidClustered Col3DPyramidStacked Col3DPyramidPercentStacked Col3DCylinder Col3DCylinderClustered Col3DCylinderStacked Col3DCylinderPercentStacked Doughnut Line Line3D Pie Pie3D PieOfPie BarOfPie Radar Scatter Surface3D WireframeSurface3D Contour WireframeContour Bubble Bubble3D )
This section defines the currently supported chart types enumeration.
type ColorMappingType byte
ColorMappingType is the type of color transformation.
Cols defines an iterator to a sheet
func (cols *Cols) Error() error
Error will return an error when the error occurs.
func (cols *Cols) Next() bool
Next will return true if the next column is found.
Rows return the current column’s row values.
Comment directly maps the comment information.
ConditionalFormatOptions directly maps the conditional format settings of the cells.
type DataIntegrity struct { EncryptedHmacKey string `xml:"encryptedHmacKey,attr"` EncryptedHmacValue string `xml:"encryptedHmacValue,attr"` }
DataIntegrity specifies the encrypted copies of the salt and hash values
used to help ensure that the integrity of the encrypted data has not been
compromised.
type DataValidation struct { AllowBlank bool `xml:"allowBlank,attr"` Error *string `xml:"error,attr"` ErrorStyle *string `xml:"errorStyle,attr"` ErrorTitle *string `xml:"errorTitle,attr"` Operator string `xml:"operator,attr,omitempty"` Prompt *string `xml:"prompt,attr"` PromptTitle *string `xml:"promptTitle,attr"` ShowDropDown bool `xml:"showDropDown,attr,omitempty"` ShowErrorMessage bool `xml:"showErrorMessage,attr,omitempty"` ShowInputMessage bool `xml:"showInputMessage,attr,omitempty"` Sqref string `xml:"sqref,attr"` Type string `xml:"type,attr,omitempty"` Formula1 string `xml:",innerxml"` Formula2 string `xml:",innerxml"` }
DataValidation directly maps the a single item of data validation defined
on a range of the worksheet.
func NewDataValidation(allowBlank bool) *DataValidation
NewDataValidation return data validation struct.
SetDropList data validation list.
SetError set error notice.
func (dv *DataValidation) SetInput(title, msg string)
SetInput set prompt notice.
func (dv *DataValidation) SetRange(f1, f2 interface{}, t DataValidationType, o DataValidationOperator) error
SetRange provides function to set data validation range in drop list, only
accepts int, float64, or string data type formula argument.
SetSqref provides function to set data validation range in drop list.
func (dv *DataValidation) SetSqrefDropList(sqref string)
SetSqrefDropList provides set data validation on a range with source
reference range of the worksheet by given data validation object and
worksheet name. The data validation object can be created by
NewDataValidation function. For example, set data validation on
Sheet1!A7:B8 with validation criteria source Sheet1!E1:E3 settings, create
in-cell dropdown by allowing list source:
dv := excelize.NewDataValidation(true) dv.Sqref = "A7:B8" dv.SetSqrefDropList("$E$1:$E$3") err := f.AddDataValidation("Sheet1", dv)
type DataValidationErrorStyle int
DataValidationErrorStyle defined the style of data validation error alert.
const ( DataValidationErrorStyleStop DataValidationErrorStyle DataValidationErrorStyleWarning DataValidationErrorStyleInformation )
Data validation error styles.
type DataValidationOperator int
DataValidationOperator operator enum.
type DataValidationType int
DataValidationType defined the type of data validation.
DefinedName directly maps the name for a cell or cell range on a
worksheet.
DocProperties directly maps the document core properties.
type EncryptedKey struct { XMLName xml.Name `xml:"http://schemas.microsoft.com/office/2006/keyEncryptor/password encryptedKey"` SpinCount int `xml:"spinCount,attr"` EncryptedVerifierHashInput string `xml:"encryptedVerifierHashInput,attr"` EncryptedVerifierHashValue string `xml:"encryptedVerifierHashValue,attr"` EncryptedKeyValue string `xml:"encryptedKeyValue,attr"` KeyData }
EncryptedKey used to generate the encrypting key.
type Encryption struct { XMLName xml.Name `xml:"encryption"` KeyData KeyData `xml:"keyData"` DataIntegrity DataIntegrity `xml:"dataIntegrity"` KeyEncryptors KeyEncryptors `xml:"keyEncryptors"` }
Encryption specifies the encryption structure, streams, and storages are
required when encrypting ECMA-376 documents.
type ErrSheetNotExist struct {
SheetName string
}
ErrSheetNotExist defines an error of sheet that does not exist
type File struct { sync.Mutex CalcChain *xlsxCalcChain ContentTypes *xlsxTypes Drawings sync.Map Path string SharedStrings *xlsxSST Sheet sync.Map SheetCount int Styles *xlsxStyleSheet Theme *xlsxTheme DecodeVMLDrawing map[string]*decodeVmlDrawing VMLDrawing map[string]*vmlDrawing WorkBook *xlsxWorkbook Relationships sync.Map Pkg sync.Map CharsetReader charsetTranscoderFn }
File define a populated spreadsheet file struct.
NewFile provides a function to create new file by default template.
For example:
f := NewFile()
OpenFile take the name of an spreadsheet file and returns a populated
spreadsheet file struct for it. For example, open spreadsheet with
password protection:
f, err := excelize.OpenFile("Book1.xlsx", excelize.Options{Password: "password"})
Close the file by Close function after opening the spreadsheet.
OpenReader read data stream from io.Reader and return a populated
spreadsheet file.
func (f *File) AddChart(sheet, cell string, chart *Chart, combo ...*Chart) error
AddChart provides the method to add chart in a sheet by given chart format
set (such as offset, scale, aspect ratio setting and print settings) and
properties set. For example, create 3D clustered column chart with data
Sheet1!$E$1:$L$15:
package main import ( "fmt" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() for idx, row := range [][]interface{}{ {nil, "Apple", "Orange", "Pear"}, {"Small", 2, 3, 3}, {"Normal", 5, 2, 4}, {"Large", 6, 7, 8}, } { cell, err := excelize.CoordinatesToCellName(1, idx+1) if err != nil { fmt.Println(err) return } f.SetSheetRow("Sheet1", cell, &row) } if err := f.AddChart("Sheet1", "E1", &excelize.Chart{ Type: excelize.Col3DClustered, Series: []excelize.ChartSeries{ { Name: "Sheet1!$A$2", Categories: "Sheet1!$B$1:$D$1", Values: "Sheet1!$B$2:$D$2", }, { Name: "Sheet1!$A$3", Categories: "Sheet1!$B$1:$D$1", Values: "Sheet1!$B$3:$D$3", }, { Name: "Sheet1!$A$4", Categories: "Sheet1!$B$1:$D$1", Values: "Sheet1!$B$4:$D$4", }, }, Title: excelize.ChartTitle{ Name: "Fruit 3D Clustered Column Chart", }, Legend: excelize.ChartLegend{ ShowLegendKey: false, }, PlotArea: excelize.ChartPlotArea{ ShowBubbleSize: true, ShowCatName: false, ShowLeaderLines: false, ShowPercent: true, ShowSerName: true, ShowVal: true, }, }); err != nil { fmt.Println(err) return } // Save spreadsheet by the given path. if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
The following shows the type of chart supported by excelize:
ID | Enumeration | Chart ----+-----------------------------+------------------------------ 0 | Area | 2D area chart 1 | AreaStacked | 2D stacked area chart 2 | AreaPercentStacked | 2D 100% stacked area chart 3 | Area3D | 3D area chart 4 | Area3DStacked | 3D stacked area chart 5 | Area3DPercentStacked | 3D 100% stacked area chart 6 | Bar | 2D clustered bar chart 7 | BarStacked | 2D stacked bar chart 8 | BarPercentStacked | 2D 100% stacked bar chart 9 | Bar3DClustered | 3D clustered bar chart 10 | Bar3DStacked | 3D stacked bar chart 11 | Bar3DPercentStacked | 3D 100% stacked bar chart 12 | Bar3DConeClustered | 3D cone clustered bar chart 13 | Bar3DConeStacked | 3D cone stacked bar chart 14 | Bar3DConePercentStacked | 3D cone percent bar chart 15 | Bar3DPyramidClustered | 3D pyramid clustered bar chart 16 | Bar3DPyramidStacked | 3D pyramid stacked bar chart 17 | Bar3DPyramidPercentStacked | 3D pyramid percent stacked bar chart 18 | Bar3DCylinderClustered | 3D cylinder clustered bar chart 19 | Bar3DCylinderStacked | 3D cylinder stacked bar chart 20 | Bar3DCylinderPercentStacked | 3D cylinder percent stacked bar chart 21 | Col | 2D clustered column chart 22 | ColStacked | 2D stacked column chart 23 | ColPercentStacked | 2D 100% stacked column chart 24 | Col3DClustered | 3D clustered column chart 25 | Col3D | 3D column chart 26 | Col3DStacked | 3D stacked column chart 27 | Col3DPercentStacked | 3D 100% stacked column chart 28 | Col3DCone | 3D cone column chart 29 | Col3DConeClustered | 3D cone clustered column chart 30 | Col3DConeStacked | 3D cone stacked column chart 31 | Col3DConePercentStacked | 3D cone percent stacked column chart 32 | Col3DPyramid | 3D pyramid column chart 33 | Col3DPyramidClustered | 3D pyramid clustered column chart 34 | Col3DPyramidStacked | 3D pyramid stacked column chart 35 | Col3DPyramidPercentStacked | 3D pyramid percent stacked column chart 36 | Col3DCylinder | 3D cylinder column chart 37 | Col3DCylinderClustered | 3D cylinder clustered column chart 38 | Col3DCylinderStacked | 3D cylinder stacked column chart 39 | Col3DCylinderPercentStacked | 3D cylinder percent stacked column chart 40 | Doughnut | doughnut chart 41 | Line | line chart 42 | Line3D | 3D line chart 43 | Pie | pie chart 44 | Pie3D | 3D pie chart 45 | PieOfPie | pie of pie chart 46 | BarOfPie | bar of pie chart 47 | Radar | radar chart 48 | Scatter | scatter chart 49 | Surface3D | 3D surface chart 50 | WireframeSurface3D | 3D wireframe surface chart 51 | Contour | contour chart 52 | WireframeContour | wireframe contour chart 53 | Bubble | bubble chart 54 | Bubble3D | 3D bubble chart
In Excel a chart series is a collection of information that defines which
data is plotted such as values, axis labels and formatting.
The series options that can be set are:
Name Categories Sizes Values Fill Line Marker
Name: Set the name for the series. The name is displayed in the chart legend
and in the formula bar. The ‘Name’ property is optional and if it isn’t
supplied it will default to Series 1..n. The name can also be a formula such
as Sheet1!$A$1
Categories: This sets the chart category labels. The category is more or less
the same as the X axis. In most chart types the ‘Categories’ property is
optional and the chart will just assume a sequential series from 1..n.
Sizes: This sets the bubble size in a data series.
Values: This is the most important property of a series and is the only
mandatory option for every chart object. This option links the chart with
the worksheet data that it displays.
Fill: This set the format for the data series fill.
Line: This sets the line format of the line chart. The ‘Line’ property is
optional and if it isn’t supplied it will default style. The options that
can be set are width and color. The range of width is 0.25pt — 999pt. If the
value of width is outside the range, the default width of the line is 2pt.
Marker: This sets the marker of the line chart and scatter chart. The range
of optional field ‘Size’ is 2-72 (default value is 5). The enumeration value
of optional field ‘Symbol’ are (default value is ‘auto’):
circle dash diamond dot none picture plus square star triangle x auto
Set properties of the chart legend. The options that can be set are:
Position ShowLegendKey
Position: Set the position of the chart legend. The default legend position
is bottom. The available positions are:
none top bottom left right top_right
ShowLegendKey: Set the legend keys shall be shown in data labels. The default
value is false.
Set properties of the chart title. The properties that can be set are:
Title
Name: Set the name (title) for the chart. The name is displayed above the
chart. The name can also be a formula such as Sheet1!$A$1 or a list with a
sheet name. The name property is optional. The default is to have no chart
title.
Specifies how blank cells are plotted on the chart by ‘ShowBlanksAs’. The
default value is gap. The options that can be set are:
gap span zero
gap: Specifies that blank values shall be left as a gap.
span: Specifies that blank values shall be spanned with a line.
zero: Specifies that blank values shall be treated as zero.
Specifies that each data marker in the series has a different color by
‘VaryColors’. The default value is true.
Set chart offset, scale, aspect ratio setting and print settings by format,
same as function ‘AddPicture’.
Set the position of the chart plot area by PlotArea. The properties that can
be set are:
SecondPlotValues ShowBubbleSize ShowCatName ShowLeaderLines ShowPercent ShowSerName ShowVal
SecondPlotValues: Specifies the values in second plot for the ‘pieOfPie’ and
‘barOfPie’ chart.
ShowBubbleSize: Specifies the bubble size shall be shown in a data label. The
‘ShowBubbleSize’ property is optional. The default value is false.
ShowCatName: Specifies that the category name shall be shown in the data
label. The ‘ShowCatName’ property is optional. The default value is true.
ShowLeaderLines: Specifies leader lines shall be shown for data labels. The
‘ShowLeaderLines’ property is optional. The default value is false.
ShowPercent: Specifies that the percentage shall be shown in a data label.
The ‘ShowPercent’ property is optional. The default value is false.
ShowSerName: Specifies that the series name shall be shown in a data label.
The ‘ShowSerName’ property is optional. The default value is false.
ShowVal: Specifies that the value shall be shown in a data label.
The ‘ShowVal’ property is optional. The default value is false.
Set the primary horizontal and vertical axis options by ‘XAxis’ and ‘YAxis’.
The properties of ‘XAxis’ that can be set are:
None MajorGridLines MinorGridLines TickLabelSkip ReverseOrder Maximum Minimum Font
The properties of ‘YAxis’ that can be set are:
None MajorGridLines MinorGridLines MajorUnit ReverseOrder Maximum Minimum Font
None: Disable axes.
MajorGridLines: Specifies major grid lines.
MinorGridLines: Specifies minor grid lines.
MajorUnit: Specifies the distance between major ticks. Shall contain a
positive floating-point number. The MajorUnit property is optional. The
default value is auto.
TickLabelSkip: Specifies how many tick labels to skip between label that is
drawn. The ‘TickLabelSkip’ property is optional. The default value is auto.
ReverseOrder: Specifies that the categories or values on reverse order
(orientation of the chart). The ReverseOrder property is optional. The
default value is false.
Maximum: Specifies that the fixed maximum, 0 is auto. The ‘Maximum’ property
is optional. The default value is auto.
Minimum: Specifies that the fixed minimum, 0 is auto. The ‘Minimum’ property
is optional. The default value is auto.
Font: Specifies that the font of the horizontal and vertical axis. The
properties of font that can be set are:
Bold Italic Underline Family Size Strike Color VertAlign
Set chart size by ‘Dimension’ property. The ‘Dimension’ property is optional.
The default width is 480, and height is 290.
combo: Specifies the create a chart that combines two or more chart types in
a single chart. For example, create a clustered column — line chart with
data Sheet1!$E$1:$L$15:
package main import ( "fmt" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() for idx, row := range [][]interface{}{ {nil, "Apple", "Orange", "Pear"}, {"Small", 2, 3, 3}, {"Normal", 5, 2, 4}, {"Large", 6, 7, 8}, } { cell, err := excelize.CoordinatesToCellName(1, idx+1) if err != nil { fmt.Println(err) return } f.SetSheetRow("Sheet1", cell, &row) } enable, disable := true, false if err := f.AddChart("Sheet1", "E1", &excelize.Chart{ Type: "col", Series: []excelize.ChartSeries{ { Name: "Sheet1!$A$2", Categories: "Sheet1!$B$1:$D$1", Values: "Sheet1!$B$2:$D$2", }, }, Format: excelize.GraphicOptions{ ScaleX: 1, ScaleY: 1, OffsetX: 15, OffsetY: 10, PrintObject: &enable, LockAspectRatio: false, Locked: &disable, }, Title: excelize.ChartTitle{ Name: "Clustered Column - Line Chart", }, Legend: excelize.ChartLegend{ Position: "left", ShowLegendKey: false, }, PlotArea: excelize.ChartPlotArea{ ShowCatName: false, ShowLeaderLines: false, ShowPercent: true, ShowSerName: true, ShowVal: true, }, }, &excelize.Chart{ Type: "line", Series: []excelize.ChartSeries{ { Name: "Sheet1!$A$4", Categories: "Sheet1!$B$1:$D$1", Values: "Sheet1!$B$4:$D$4", Marker: excelize.ChartMarker{ Symbol: "none", Size: 10, }, }, }, Format: excelize.GraphicOptions{ ScaleX: 1, ScaleY: 1, OffsetX: 15, OffsetY: 10, PrintObject: &enable, LockAspectRatio: false, Locked: &disable, }, Legend: excelize.ChartLegend{ Position: "right", ShowLegendKey: false, }, PlotArea: excelize.ChartPlotArea{ ShowCatName: false, ShowLeaderLines: false, ShowPercent: true, ShowSerName: true, ShowVal: true, }, }); err != nil { fmt.Println(err) return } // Save spreadsheet by the given path. if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
func (f *File) AddChartSheet(sheet string, chart *Chart, combo ...*Chart) error
AddChartSheet provides the method to create a chartsheet by given chart
format set (such as offset, scale, aspect ratio setting and print settings)
and properties set. In Excel a chartsheet is a worksheet that only contains
a chart.
AddComment provides the method to add comment in a sheet by given worksheet
index, cell and format set (such as author and text). Note that the max
author length is 255 and the max text length is 32512. For example, add a
comment in Sheet1!$A$30:
err := f.AddComment("Sheet1", excelize.Comment{ Cell: "A12", Author: "Excelize", Runs: []excelize.RichTextRun{ {Text: "Excelize: ", Font: &excelize.Font{Bold: true}}, {Text: "This is a comment."}, }, })
AddDataValidation provides set data validation on a range of the worksheet
by given data validation object and worksheet name. The data validation
object can be created by NewDataValidation function.
Example 1, set data validation on Sheet1!A1:B2 with validation criteria
settings, show error alert after invalid data is entered with «Stop» style
and custom title «error body»:
dv := excelize.NewDataValidation(true) dv.Sqref = "A1:B2" dv.SetRange(10, 20, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorBetween) dv.SetError(excelize.DataValidationErrorStyleStop, "error title", "error body") err := f.AddDataValidation("Sheet1", dv)
Example 2, set data validation on Sheet1!A3:B4 with validation criteria
settings, and show input message when cell is selected:
dv = excelize.NewDataValidation(true) dv.Sqref = "A3:B4" dv.SetRange(10, 20, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorGreaterThan) dv.SetInput("input title", "input body") err = f.AddDataValidation("Sheet1", dv)
Example 3, set data validation on Sheet1!A5:B6 with validation criteria
settings, create in-cell dropdown by allowing list source:
dv = excelize.NewDataValidation(true) dv.Sqref = "A5:B6" dv.SetDropList([]string{"1", "2", "3"}) err = f.AddDataValidation("Sheet1", dv)
AddPicture provides the method to add picture in a sheet by given picture
format set (such as offset, scale, aspect ratio setting and print settings)
and file path, supported image types: BMP, EMF, EMZ, GIF, JPEG, JPG, PNG,
SVG, TIF, TIFF, WMF, and WMZ. This function is concurrency safe. For example:
package main import ( "fmt" _ "image/gif" _ "image/jpeg" _ "image/png" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() // Insert a picture. if err := f.AddPicture("Sheet1", "A2", "image.jpg", nil); err != nil { fmt.Println(err) return } // Insert a picture scaling in the cell with location hyperlink. enable := true if err := f.AddPicture("Sheet1", "D2", "image.png", &excelize.GraphicOptions{ ScaleX: 0.5, ScaleY: 0.5, Hyperlink: "#Sheet2!D8", HyperlinkType: "Location", }, ); err != nil { fmt.Println(err) return } // Insert a picture offset in the cell with external hyperlink, printing and positioning support. if err := f.AddPicture("Sheet1", "H2", "image.gif", &excelize.GraphicOptions{ PrintObject: &enable, LockAspectRatio: false, OffsetX: 15, OffsetY: 10, Hyperlink: "https://github.com/xuri/excelize", HyperlinkType: "External", Positioning: "oneCell", }, ); err != nil { fmt.Println(err) return } if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
The optional parameter «AutoFit» specifies if you make image size auto-fits the
cell, the default value of that is ‘false’.
The optional parameter «Hyperlink» specifies the hyperlink of the image.
The optional parameter «HyperlinkType» defines two types of
hyperlink «External» for website or «Location» for moving to one of the
cells in this workbook. When the «HyperlinkType» is «Location»,
coordinates need to start with «#».
The optional parameter «Positioning» defines two types of the position of an
image in an Excel spreadsheet, «oneCell» (Move but don’t size with
cells) or «absolute» (Don’t move or size with cells). If you don’t set this
parameter, the default positioning is move and size with cells.
The optional parameter «PrintObject» indicates whether the image is printed
when the worksheet is printed, the default value of that is ‘true’.
The optional parameter «LockAspectRatio» indicates whether lock aspect
ratio for the image, the default value of that is ‘false’.
The optional parameter «Locked» indicates whether lock the image. Locking
an object has no effect unless the sheet is protected.
The optional parameter «OffsetX» specifies the horizontal offset of the
image with the cell, the default value of that is 0.
The optional parameter «ScaleX» specifies the horizontal scale of images,
the default value of that is 1.0 which presents 100%.
The optional parameter «OffsetY» specifies the vertical offset of the
image with the cell, the default value of that is 0.
The optional parameter «ScaleY» specifies the vertical scale of images,
the default value of that is 1.0 which presents 100%.
func (f *File) AddPictureFromBytes(sheet, cell string, pic *Picture) error
AddPictureFromBytes provides the method to add picture in a sheet by given
picture format set (such as offset, scale, aspect ratio setting and print
settings), file base name, extension name and file bytes, supported image
types: EMF, EMZ, GIF, JPEG, JPG, PNG, SVG, TIF, TIFF, WMF, and WMZ. For
example:
package main import ( "fmt" _ "image/jpeg" "os" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() file, err := os.ReadFile("image.jpg") if err != nil { fmt.Println(err) return } if err := f.AddPictureFromBytes("Sheet1", "A2", &excelize.Picture{ Extension: ".jpg", File: file, Format: &excelize.GraphicOptions{AltText: "Excel Logo"}, }); err != nil { fmt.Println(err) return } if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
func (f *File) AddPivotTable(opts *PivotTableOptions) error
AddPivotTable provides the method to add pivot table by given pivot table
options. Note that the same fields can not in Columns, Rows and Filter
fields at the same time.
For example, create a pivot table on the range reference Sheet1!$G$2:$M$34
with the range reference Sheet1!$A$1:$E$31 as the data source, summarize by
sum for sales:
package main import ( "fmt" "math/rand" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() // Create some data in a sheet month := []string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} year := []int{2017, 2018, 2019} types := []string{"Meat", "Dairy", "Beverages", "Produce"} region := []string{"East", "West", "North", "South"} f.SetSheetRow("Sheet1", "A1", &[]string{"Month", "Year", "Type", "Sales", "Region"}) for row := 2; row < 32; row++ { f.SetCellValue("Sheet1", fmt.Sprintf("A%d", row), month[rand.Intn(12)]) f.SetCellValue("Sheet1", fmt.Sprintf("B%d", row), year[rand.Intn(3)]) f.SetCellValue("Sheet1", fmt.Sprintf("C%d", row), types[rand.Intn(4)]) f.SetCellValue("Sheet1", fmt.Sprintf("D%d", row), rand.Intn(5000)) f.SetCellValue("Sheet1", fmt.Sprintf("E%d", row), region[rand.Intn(4)]) } if err := f.AddPivotTable(&excelize.PivotTableOptions{ DataRange: "Sheet1!$A$1:$E$31", PivotTableRange: "Sheet1!$G$2:$M$34", Rows: []excelize.PivotTableField{{Data: "Month", DefaultSubtotal: true}, {Data: "Year"}}, Filter: []excelize.PivotTableField{{Data: "Region"}}, Columns: []excelize.PivotTableField{{Data: "Type", DefaultSubtotal: true}}, Data: []excelize.PivotTableField{{Data: "Sales", Name: "Summarize", Subtotal: "Sum"}}, RowGrandTotals: true, ColGrandTotals: true, ShowDrill: true, ShowRowHeaders: true, ShowColHeaders: true, ShowLastColumn: true, }); err != nil { fmt.Println(err) } if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
AddShape provides the method to add shape in a sheet by given worksheet
index, shape format set (such as offset, scale, aspect ratio setting and
print settings) and properties set. For example, add text box (rect shape)
in Sheet1:
lineWidth := 1.2 err := f.AddShape("Sheet1", "G6", &excelize.Shape{ Type: "rect", Line: excelize.ShapeLine{Color: "4286F4", Width: &lineWidth}, Fill: excelize.Fill{Color: []string{"8EB9FF"}, Pattern: 1}, Paragraph: []excelize.RichTextRun{ { Text: "Rectangle Shape", Font: &excelize.Font{ Bold: true, Italic: true, Family: "Times New Roman", Size: 18, Color: "777777", Underline: "sng", }, }, }, Width: 180, Height: 40, }, )
The following shows the type of shape supported by excelize:
accentBorderCallout1 (Callout 1 with Border and Accent Shape) accentBorderCallout2 (Callout 2 with Border and Accent Shape) accentBorderCallout3 (Callout 3 with Border and Accent Shape) accentCallout1 (Callout 1 Shape) accentCallout2 (Callout 2 Shape) accentCallout3 (Callout 3 Shape) actionButtonBackPrevious (Back or Previous Button Shape) actionButtonBeginning (Beginning Button Shape) actionButtonBlank (Blank Button Shape) actionButtonDocument (Document Button Shape) actionButtonEnd (End Button Shape) actionButtonForwardNext (Forward or Next Button Shape) actionButtonHelp (Help Button Shape) actionButtonHome (Home Button Shape) actionButtonInformation (Information Button Shape) actionButtonMovie (Movie Button Shape) actionButtonReturn (Return Button Shape) actionButtonSound (Sound Button Shape) arc (Curved Arc Shape) bentArrow (Bent Arrow Shape) bentConnector2 (Bent Connector 2 Shape) bentConnector3 (Bent Connector 3 Shape) bentConnector4 (Bent Connector 4 Shape) bentConnector5 (Bent Connector 5 Shape) bentUpArrow (Bent Up Arrow Shape) bevel (Bevel Shape) blockArc (Block Arc Shape) borderCallout1 (Callout 1 with Border Shape) borderCallout2 (Callout 2 with Border Shape) borderCallout3 (Callout 3 with Border Shape) bracePair (Brace Pair Shape) bracketPair (Bracket Pair Shape) callout1 (Callout 1 Shape) callout2 (Callout 2 Shape) callout3 (Callout 3 Shape) can (Can Shape) chartPlus (Chart Plus Shape) chartStar (Chart Star Shape) chartX (Chart X Shape) chevron (Chevron Shape) chord (Chord Shape) circularArrow (Circular Arrow Shape) cloud (Cloud Shape) cloudCallout (Callout Cloud Shape) corner (Corner Shape) cornerTabs (Corner Tabs Shape) cube (Cube Shape) curvedConnector2 (Curved Connector 2 Shape) curvedConnector3 (Curved Connector 3 Shape) curvedConnector4 (Curved Connector 4 Shape) curvedConnector5 (Curved Connector 5 Shape) curvedDownArrow (Curved Down Arrow Shape) curvedLeftArrow (Curved Left Arrow Shape) curvedRightArrow (Curved Right Arrow Shape) curvedUpArrow (Curved Up Arrow Shape) decagon (Decagon Shape) diagStripe (Diagonal Stripe Shape) diamond (Diamond Shape) dodecagon (Dodecagon Shape) donut (Donut Shape) doubleWave (Double Wave Shape) downArrow (Down Arrow Shape) downArrowCallout (Callout Down Arrow Shape) ellipse (Ellipse Shape) ellipseRibbon (Ellipse Ribbon Shape) ellipseRibbon2 (Ellipse Ribbon 2 Shape) flowChartAlternateProcess (Alternate Process Flow Shape) flowChartCollate (Collate Flow Shape) flowChartConnector (Connector Flow Shape) flowChartDecision (Decision Flow Shape) flowChartDelay (Delay Flow Shape) flowChartDisplay (Display Flow Shape) flowChartDocument (Document Flow Shape) flowChartExtract (Extract Flow Shape) flowChartInputOutput (Input Output Flow Shape) flowChartInternalStorage (Internal Storage Flow Shape) flowChartMagneticDisk (Magnetic Disk Flow Shape) flowChartMagneticDrum (Magnetic Drum Flow Shape) flowChartMagneticTape (Magnetic Tape Flow Shape) flowChartManualInput (Manual Input Flow Shape) flowChartManualOperation (Manual Operation Flow Shape) flowChartMerge (Merge Flow Shape) flowChartMultidocument (Multi-Document Flow Shape) flowChartOfflineStorage (Offline Storage Flow Shape) flowChartOffpageConnector (Off-Page Connector Flow Shape) flowChartOnlineStorage (Online Storage Flow Shape) flowChartOr (Or Flow Shape) flowChartPredefinedProcess (Predefined Process Flow Shape) flowChartPreparation (Preparation Flow Shape) flowChartProcess (Process Flow Shape) flowChartPunchedCard (Punched Card Flow Shape) flowChartPunchedTape (Punched Tape Flow Shape) flowChartSort (Sort Flow Shape) flowChartSummingJunction (Summing Junction Flow Shape) flowChartTerminator (Terminator Flow Shape) foldedCorner (Folded Corner Shape) frame (Frame Shape) funnel (Funnel Shape) gear6 (Gear 6 Shape) gear9 (Gear 9 Shape) halfFrame (Half Frame Shape) heart (Heart Shape) heptagon (Heptagon Shape) hexagon (Hexagon Shape) homePlate (Home Plate Shape) horizontalScroll (Horizontal Scroll Shape) irregularSeal1 (Irregular Seal 1 Shape) irregularSeal2 (Irregular Seal 2 Shape) leftArrow (Left Arrow Shape) leftArrowCallout (Callout Left Arrow Shape) leftBrace (Left Brace Shape) leftBracket (Left Bracket Shape) leftCircularArrow (Left Circular Arrow Shape) leftRightArrow (Left Right Arrow Shape) leftRightArrowCallout (Callout Left Right Arrow Shape) leftRightCircularArrow (Left Right Circular Arrow Shape) leftRightRibbon (Left Right Ribbon Shape) leftRightUpArrow (Left Right Up Arrow Shape) leftUpArrow (Left Up Arrow Shape) lightningBolt (Lightning Bolt Shape) line (Line Shape) lineInv (Line Inverse Shape) mathDivide (Divide Math Shape) mathEqual (Equal Math Shape) mathMinus (Minus Math Shape) mathMultiply (Multiply Math Shape) mathNotEqual (Not Equal Math Shape) mathPlus (Plus Math Shape) moon (Moon Shape) nonIsoscelesTrapezoid (Non-Isosceles Trapezoid Shape) noSmoking (No Smoking Shape) notchedRightArrow (Notched Right Arrow Shape) octagon (Octagon Shape) parallelogram (Parallelogram Shape) pentagon (Pentagon Shape) pie (Pie Shape) pieWedge (Pie Wedge Shape) plaque (Plaque Shape) plaqueTabs (Plaque Tabs Shape) plus (Plus Shape) quadArrow (Quad-Arrow Shape) quadArrowCallout (Callout Quad-Arrow Shape) rect (Rectangle Shape) ribbon (Ribbon Shape) ribbon2 (Ribbon 2 Shape) rightArrow (Right Arrow Shape) rightArrowCallout (Callout Right Arrow Shape) rightBrace (Right Brace Shape) rightBracket (Right Bracket Shape) round1Rect (One Round Corner Rectangle Shape) round2DiagRect (Two Diagonal Round Corner Rectangle Shape) round2SameRect (Two Same-side Round Corner Rectangle Shape) roundRect (Round Corner Rectangle Shape) rtTriangle (Right Triangle Shape) smileyFace (Smiley Face Shape) snip1Rect (One Snip Corner Rectangle Shape) snip2DiagRect (Two Diagonal Snip Corner Rectangle Shape) snip2SameRect (Two Same-side Snip Corner Rectangle Shape) snipRoundRect (One Snip One Round Corner Rectangle Shape) squareTabs (Square Tabs Shape) star10 (Ten Pointed Star Shape) star12 (Twelve Pointed Star Shape) star16 (Sixteen Pointed Star Shape) star24 (Twenty Four Pointed Star Shape) star32 (Thirty Two Pointed Star Shape) star4 (Four Pointed Star Shape) star5 (Five Pointed Star Shape) star6 (Six Pointed Star Shape) star7 (Seven Pointed Star Shape) star8 (Eight Pointed Star Shape) straightConnector1 (Straight Connector 1 Shape) stripedRightArrow (Striped Right Arrow Shape) sun (Sun Shape) swooshArrow (Swoosh Arrow Shape) teardrop (Teardrop Shape) trapezoid (Trapezoid Shape) triangle (Triangle Shape) upArrow (Up Arrow Shape) upArrowCallout (Callout Up Arrow Shape) upDownArrow (Up Down Arrow Shape) upDownArrowCallout (Callout Up Down Arrow Shape) uturnArrow (U-Turn Arrow Shape) verticalScroll (Vertical Scroll Shape) wave (Wave Shape) wedgeEllipseCallout (Callout Wedge Ellipse Shape) wedgeRectCallout (Callout Wedge Rectangle Shape) wedgeRoundRectCallout (Callout Wedge Round Rectangle Shape)
The following shows the type of text underline supported by excelize:
none words sng dbl heavy dotted dottedHeavy dash dashHeavy dashLong dashLongHeavy dotDash dotDashHeavy dotDotDash dotDotDashHeavy wavy wavyHeavy wavyDbl
AddSparkline provides a function to add sparklines to the worksheet by
given formatting options. Sparklines are small charts that fit in a single
cell and are used to show trends in data. Sparklines are a feature of Excel
2010 and later only. You can write them to an XLSX file that can be read by
Excel 2007, but they won’t be displayed. For example, add a grouped
sparkline. Changes are applied to all three:
err := f.AddSparkline("Sheet1", &excelize.SparklineOptions{ Location: []string{"A1", "A2", "A3"}, Range: []string{"Sheet2!A1:J1", "Sheet2!A2:J2", "Sheet2!A3:J3"}, Markers: true, })
The following shows the formatting options of sparkline supported by excelize:
Parameter | Description -------------+-------------------------------------------- Location | Required, must have the same number with 'Range' parameter Range | Required, must have the same number with 'Location' parameter Type | Enumeration value: line, column, win_loss Style | Value range: 0 - 35 Hight | Toggle sparkline high points Low | Toggle sparkline low points First | Toggle sparkline first points Last | Toggle sparkline last points Negative | Toggle sparkline negative points Markers | Toggle sparkline markers Axis | Used to specify if show horizontal axis Reverse | Used to specify if enable plot data right-to-left SeriesColor | An RGB Color is specified as RRGGBB
AddTable provides the method to add table in a worksheet by given worksheet
name, range reference and format set. For example, create a table of A1:D5
on Sheet1:
err := f.AddTable("Sheet1", &excelize.Table{Range: "A1:D5"})
Create a table of F2:H6 on Sheet2 with format set:
disable := false err := f.AddTable("Sheet2", &excelize.Table{ Range: "F2:H6", Name: "table", StyleName: "TableStyleMedium2", ShowFirstColumn: true, ShowLastColumn: true, ShowRowStripes: &disable, ShowColumnStripes: true, })
Note that the table must be at least two lines including the header. The
header cells must contain strings and must be unique, and must set the
header row data of the table before calling the AddTable function. Multiple
tables range reference that can’t have an intersection.
Name: The name of the table, in the same worksheet name of the table should
be unique, starts with a letter or underscore (_), doesn’t include a
space or character, and should be no more than 255 characters
StyleName: The built-in table style names
TableStyleLight1 - TableStyleLight21 TableStyleMedium1 - TableStyleMedium28 TableStyleDark1 - TableStyleDark11
AddVBAProject provides the method to add vbaProject.bin file which contains
functions and/or macros. The file extension should be XLSM or XLTM. For
example:
codeName := "Sheet1" if err := f.SetSheetProps("Sheet1", &excelize.SheetPropsOptions{ CodeName: &codeName, }); err != nil { fmt.Println(err) return } file, err := os.ReadFile("vbaProject.bin") if err != nil { fmt.Println(err) return } if err := f.AddVBAProject(file); err != nil { fmt.Println(err) return } if err := f.SaveAs("macros.xlsm"); err != nil { fmt.Println(err) return }
AutoFilter provides the method to add auto filter in a worksheet by given
worksheet name, range reference and settings. An auto filter in Excel is a
way of filtering a 2D range of data based on some simple criteria. For
example applying an auto filter to a cell range A1:D4 in the Sheet1:
err := f.AutoFilter("Sheet1", "A1:D4", []excelize.AutoFilterOptions{})
Filter data in an auto filter:
err := f.AutoFilter("Sheet1", "A1:D4", []excelize.AutoFilterOptions{ {Column: "B", Expression: "x != blanks"}, })
Column defines the filter columns in an auto filter range based on simple
criteria
It isn’t sufficient to just specify the filter condition. You must also
hide any rows that don’t match the filter condition. Rows are hidden using
the SetRowVisible function. Excelize can’t filter rows automatically since
this isn’t part of the file format.
Setting a filter criteria for a column:
Expression defines the conditions, the following operators are available
for setting the filter criteria:
== != > < >= <= and or
An expression can comprise a single statement or two statements separated
by the ‘and’ and ‘or’ operators. For example:
x < 2000 x > 2000 x == 2000 x > 2000 and x < 5000 x == 2000 or x == 5000
Filtering of blank or non-blank data can be achieved by using a value of
Blanks or NonBlanks in the expression:
x == Blanks x == NonBlanks
Excel also allows some simple string matching operations:
x == b* // begins with b x != b* // doesn't begin with b x == *b // ends with b x != *b // doesn't end with b x == *b* // contains b x != *b* // doesn't contains b
You can also use ‘*’ to match any character or number and ‘?’ to match any
single character or number. No other regular expression quantifier is
supported by Excel’s filters. Excel’s regular expression characters can be
escaped using ‘~’.
The placeholder variable x in the above examples can be replaced by any
simple string. The actual placeholder name is ignored internally so the
following are all equivalent:
x < 2000 col < 2000 Price < 2000
CalcCellValue provides a function to get calculated cell value. This feature
is currently in working processing. Iterative calculation, implicit
intersection, explicit intersection, array formula, table formula and some
other formulas are not supported currently.
Supported formula functions:
ABS ACCRINT ACCRINTM ACOS ACOSH ACOT ACOTH ADDRESS AGGREGATE AMORDEGRC AMORLINC AND ARABIC ASIN ASINH ATAN ATAN2 ATANH AVEDEV AVERAGE AVERAGEA AVERAGEIF AVERAGEIFS BASE BESSELI BESSELJ BESSELK BESSELY BETADIST BETA.DIST BETAINV BETA.INV BIN2DEC BIN2HEX BIN2OCT BINOMDIST BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR CEILING CEILING.MATH CEILING.PRECISE CHAR CHIDIST CHIINV CHITEST CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSE CLEAN CODE COLUMN COLUMNS COMBIN COMBINA COMPLEX CONCAT CONCATENATE CONFIDENCE CONFIDENCE.NORM CONFIDENCE.T CONVERT CORREL COS COSH COT COTH COUNT COUNTA COUNTBLANK COUNTIF COUNTIFS COUPDAYBS COUPDAYS COUPDAYSNC COUPNCD COUPNUM COUPPCD COVAR COVARIANCE.P COVARIANCE.S CRITBINOM CSC CSCH CUMIPMT CUMPRINC DATE DATEDIF DATEVALUE DAVERAGE DAY DAYS DAYS360 DB DCOUNT DCOUNTA DDB DEC2BIN DEC2HEX DEC2OCT DECIMAL DEGREES DELTA DEVSQ DGET DISC DMAX DMIN DOLLARDE DOLLARFR DPRODUCT DSTDEV DSTDEVP DSUM DURATION DVAR DVARP EFFECT EDATE ENCODEURL EOMONTH ERF ERF.PRECISE ERFC ERFC.PRECISE ERROR.TYPE EUROCONVERT EVEN EXACT EXP EXPON.DIST EXPONDIST FACT FACTDOUBLE FALSE F.DIST F.DIST.RT FDIST FIND FINDB F.INV F.INV.RT FINV FISHER FISHERINV FIXED FLOOR FLOOR.MATH FLOOR.PRECISE FORMULATEXT F.TEST FTEST FV FVSCHEDULE GAMMA GAMMA.DIST GAMMADIST GAMMA.INV GAMMAINV GAMMALN GAMMALN.PRECISE GAUSS GCD GEOMEAN GESTEP GROWTH HARMEAN HEX2BIN HEX2DEC HEX2OCT HLOOKUP HOUR HYPERLINK HYPGEOM.DIST HYPGEOMDIST IF IFERROR IFNA IFS IMABS IMAGINARY IMARGUMENT IMCONJUGATE IMCOS IMCOSH IMCOT IMCSC IMCSCH IMDIV IMEXP IMLN IMLOG10 IMLOG2 IMPOWER IMPRODUCT IMREAL IMSEC IMSECH IMSIN IMSINH IMSQRT IMSUB IMSUM IMTAN INDEX INDIRECT INT INTRATE IPMT IRR ISBLANK ISERR ISERROR ISEVEN ISFORMULA ISLOGICAL ISNA ISNONTEXT ISNUMBER ISODD ISREF ISTEXT ISO.CEILING ISOWEEKNUM ISPMT KURT LARGE LCM LEFT LEFTB LEN LENB LN LOG LOG10 LOGINV LOGNORM.DIST LOGNORMDIST LOGNORM.INV LOOKUP LOWER MATCH MAX MAXA MAXIFS MDETERM MDURATION MEDIAN MID MIDB MIN MINA MINIFS MINUTE MINVERSE MIRR MMULT MOD MODE MODE.MULT MODE.SNGL MONTH MROUND MULTINOMIAL MUNIT N NA NEGBINOM.DIST NEGBINOMDIST NETWORKDAYS NETWORKDAYS.INTL NOMINAL NORM.DIST NORMDIST NORM.INV NORMINV NORM.S.DIST NORMSDIST NORM.S.INV NORMSINV NOT NOW NPER NPV OCT2BIN OCT2DEC OCT2HEX ODD ODDFPRICE OR PDURATION PEARSON PERCENTILE.EXC PERCENTILE.INC PERCENTILE PERCENTRANK.EXC PERCENTRANK.INC PERCENTRANK PERMUT PERMUTATIONA PHI PI PMT POISSON.DIST POISSON POWER PPMT PRICE PRICEDISC PRICEMAT PRODUCT PROPER PV QUARTILE QUARTILE.EXC QUARTILE.INC QUOTIENT RADIANS RAND RANDBETWEEN RANK RANK.EQ RATE RECEIVED REPLACE REPLACEB REPT RIGHT RIGHTB ROMAN ROUND ROUNDDOWN ROUNDUP ROW ROWS RRI RSQ SEC SECH SECOND SERIESSUM SHEET SHEETS SIGN SIN SINH SKEW SKEW.P SLN SLOPE SMALL SQRT SQRTPI STANDARDIZE STDEV STDEV.P STDEV.S STDEVA STDEVP STDEVPA STEYX SUBSTITUTE SUBTOTAL SUM SUMIF SUMIFS SUMPRODUCT SUMSQ SUMX2MY2 SUMX2PY2 SUMXMY2 SWITCH SYD T TAN TANH TBILLEQ TBILLPRICE TBILLYIELD T.DIST T.DIST.2T T.DIST.RT TDIST TEXTJOIN TIME TIMEVALUE T.INV T.INV.2T TINV TODAY TRANSPOSE TREND TRIM TRIMMEAN TRUE TRUNC T.TEST TTEST TYPE UNICHAR UNICODE UPPER VALUE VAR VAR.P VAR.S VARA VARP VARPA VDB VLOOKUP WEEKDAY WEEKNUM WEIBULL WEIBULL.DIST WORKDAY WORKDAY.INTL XIRR XLOOKUP XNPV XOR YEAR YEARFRAC YIELD YIELDDISC YIELDMAT Z.TEST ZTEST
func (f *File) CharsetTranscoder(fn charsetTranscoderFn) *File
CharsetTranscoder Set user defined codepage transcoder function for open
XLSX from non UTF-8 encoding.
Close closes and cleanup the open temporary file for the spreadsheet.
Cols returns a columns iterator, used for streaming reading data for a
worksheet with a large data. This function is concurrency safe. For
example:
cols, err := f.Cols("Sheet1") if err != nil { fmt.Println(err) return } for cols.Next() { col, err := cols.Rows() if err != nil { fmt.Println(err) } for _, rowCell := range col { fmt.Print(rowCell, "t") } fmt.Println() }
CopySheet provides a function to duplicate a worksheet by gave source and
target worksheet index. Note that currently doesn’t support duplicate
workbooks that contain tables, charts or pictures. For Example:
// Sheet1 already exists... index, err := f.NewSheet("Sheet2") if err != nil { fmt.Println(err) return } err := f.CopySheet(1, index)
DeleteChart provides a function to delete chart in spreadsheet by given
worksheet name and cell reference.
DeleteComment provides the method to delete comment in a sheet by given
worksheet name. For example, delete the comment in Sheet1!$A$30:
err := f.DeleteComment("Sheet1", "A30")
DeleteDataValidation delete data validation by given worksheet name and
reference sequence. All data validations in the worksheet will be deleted
if not specify reference sequence parameter.
func (f *File) DeleteDefinedName(definedName *DefinedName) error
DeleteDefinedName provides a function to delete the defined names of the
workbook or worksheet. If not specified scope, the default scope is
workbook. For example:
err := f.DeleteDefinedName(&excelize.DefinedName{ Name: "Amount", Scope: "Sheet2", })
DeletePicture provides a function to delete all pictures in a cell by given
worksheet name and cell reference. Note that the image file won’t be deleted
from the document currently.
DeleteSheet provides a function to delete worksheet in a workbook by given
worksheet name. Use this method with caution, which will affect changes in
references such as formulas, charts, and so on. If there is any referenced
value of the deleted worksheet, it will cause a file error when you open
it. This function will be invalid when only one worksheet is left.
DuplicateRow inserts a copy of specified row (by its Excel row number) below
err := f.DuplicateRow("Sheet1", 2)
Use this method with caution, which will affect changes in references such
as formulas, charts, and so on. If there is any referenced value of the
worksheet, it will cause a file error when you open it. The excelize only
partially updates these references currently.
DuplicateRowTo inserts a copy of specified row by it Excel number
to specified row position moving down exists rows after target position
err := f.DuplicateRowTo("Sheet1", 2, 7)
Use this method with caution, which will affect changes in references such
as formulas, charts, and so on. If there is any referenced value of the
worksheet, it will cause a file error when you open it. The excelize only
partially updates these references currently.
func (f *File) GetActiveSheetIndex() (index int)
GetActiveSheetIndex provides a function to get active sheet index of the
spreadsheet. If not found the active sheet will be return integer 0.
func (f *File) GetAppProps() (ret *AppProperties, err error)
GetAppProps provides a function to get document application properties.
GetCellFormula provides a function to get formula from cell by given
worksheet name and cell reference in spreadsheet.
GetCellHyperLink gets a cell hyperlink based on the given worksheet name and
cell reference. If the cell has a hyperlink, it will return ‘true’ and
the link address, otherwise it will return ‘false’ and an empty link
address.
For example, get a hyperlink to a ‘H6’ cell on a worksheet named ‘Sheet1’:
link, target, err := f.GetCellHyperLink("Sheet1", "H6")
func (f *File) GetCellRichText(sheet, cell string) (runs []RichTextRun, err error)
GetCellRichText provides a function to get rich text of cell by given
worksheet.
GetCellStyle provides a function to get cell style index by given worksheet
name and cell reference.
GetCellType provides a function to get the cell’s data type by given
worksheet name and cell reference in spreadsheet file.
GetCellValue provides a function to get formatted value from cell by given
worksheet name and cell reference in spreadsheet. The return value is
converted to the ‘string’ data type. This function is concurrency safe. If
the cell format can be applied to the value of a cell, the applied value
will be returned, otherwise the original value will be returned. All cells’
values will be the same in a merged range.
GetColOutlineLevel provides a function to get outline level of a single
column by given worksheet name and column name. For example, get outline
level of column D in Sheet1:
level, err := f.GetColOutlineLevel("Sheet1", "D")
GetColStyle provides a function to get column style ID by given worksheet
name and column name. This function is concurrency safe.
GetColVisible provides a function to get visible of a single column by given
worksheet name and column name. This function is concurrency safe. For
example, get visible state of column D in Sheet1:
visible, err := f.GetColVisible("Sheet1", "D")
GetColWidth provides a function to get column width by given worksheet name
and column name. This function is concurrency safe.
GetCols gets the value of all cells by columns on the worksheet based on the
given worksheet name, returned as a two-dimensional array, where the value
of the cell is converted to the `string` type. If the cell format can be
applied to the value of the cell, the applied value will be used, otherwise
the original value will be used.
For example, get and traverse the value of all cells by columns on a
worksheet named
‘Sheet1’:
cols, err := f.GetCols("Sheet1") if err != nil { fmt.Println(err) return } for _, col := range cols { for _, rowCell := range col { fmt.Print(rowCell, "t") } fmt.Println() }
GetComments retrieves all comments in a worksheet by given worksheet name.
GetConditionalFormats returns conditional format settings by given worksheet
name.
GetDataValidations returns data validations list by given worksheet name.
GetDefaultFont provides the default font name currently set in the
workbook. The spreadsheet generated by excelize default font is Calibri.
func (f *File) GetDefinedName() []DefinedName
GetDefinedName provides a function to get the defined names of the workbook
or worksheet.
func (f *File) GetDocProps() (ret *DocProperties, err error)
GetDocProps provides a function to get document core properties.
GetMergeCells provides a function to get all merged cells from a worksheet
currently.
GetPageLayout provides a function to gets worksheet page layout.
GetPageMargins provides a function to get worksheet page margins.
GetPictures provides a function to get picture meta info and raw content
embed in spreadsheet by given worksheet and cell name. This function
returns the image contents as []byte data types. This function is
concurrency safe. For example:
f, err := excelize.OpenFile("Book1.xlsx") if err != nil { fmt.Println(err) return } defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() pics, err := f.GetPictures("Sheet1", "A2") if err != nil { fmt.Println(err) } for idx, pic := range pics { name := fmt.Sprintf("image%d%s", idx+1, pic.Extension) if err := os.WriteFile(name, pic.File, 0644); err != nil { fmt.Println(err) } }
GetRowHeight provides a function to get row height by given worksheet name
and row number. For example, get the height of the first row in Sheet1:
height, err := f.GetRowHeight("Sheet1", 1)
GetRowOutlineLevel provides a function to get outline level number of a
single row by given worksheet name and Excel row number. For example, get
outline number of row 2 in Sheet1:
level, err := f.GetRowOutlineLevel("Sheet1", 2)
GetRowVisible provides a function to get visible of a single row by given
worksheet name and Excel row number. For example, get visible state of row
2 in Sheet1:
visible, err := f.GetRowVisible("Sheet1", 2)
GetRows return all the rows in a sheet by given worksheet name, returned as
a two-dimensional array, where the value of the cell is converted to the
string type. If the cell format can be applied to the value of the cell,
the applied value will be used, otherwise the original value will be used.
GetRows fetched the rows with value or formula cells, the continually blank
cells in the tail of each row will be skipped, so the length of each row
may be inconsistent.
For example, get and traverse the value of all cells by rows on a worksheet
named ‘Sheet1’:
rows, err := f.GetRows("Sheet1") if err != nil { fmt.Println(err) return } for _, row := range rows { for _, colCell := range row { fmt.Print(colCell, "t") } fmt.Println() }
GetSheetDimension provides the method to get the used range of the worksheet.
GetSheetIndex provides a function to get a sheet index of the workbook by
the given sheet name. If the given sheet name is invalid or sheet doesn’t
exist, it will return an integer type value -1.
func (f *File) GetSheetList() (list []string)
GetSheetList provides a function to get worksheets, chart sheets, and
dialog sheets name list of the workbook.
GetSheetMap provides a function to get worksheets, chart sheets, dialog
sheets ID and name map of the workbook. For example:
f, err := excelize.OpenFile("Book1.xlsx") if err != nil { return } defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() for index, name := range f.GetSheetMap() { fmt.Println(index, name) }
func (f *File) GetSheetName(index int) (name string)
GetSheetName provides a function to get the sheet name of the workbook by
the given sheet index. If the given sheet index is invalid, it will return
an empty string.
GetSheetProps provides a function to get worksheet properties.
GetSheetView gets the value of sheet view options. The viewIndex may be
negative and if so is counted backward (-1 is the last view).
GetSheetVisible provides a function to get worksheet visible by given worksheet
name. For example, get visible state of Sheet1:
visible, err := f.GetSheetVisible("Sheet1")
func (f *File) GetWorkbookProps() (WorkbookPropsOptions, error)
GetWorkbookProps provides a function to gets workbook properties.
GroupSheets provides a function to group worksheets by given worksheets
name. Group worksheets must contain an active worksheet.
InsertCols provides a function to insert new columns before the given column
name and number of columns. For example, create two columns before column
C in Sheet1:
err := f.InsertCols("Sheet1", "C", 2)
Use this method with caution, which will affect changes in references such
as formulas, charts, and so on. If there is any referenced value of the
worksheet, it will cause a file error when you open it. The excelize only
partially updates these references currently.
InsertPageBreak create a page break to determine where the printed page
ends and where begins the next one by given worksheet name and cell
reference, so the content before the page break will be printed on one page
and after the page break on another.
InsertRows provides a function to insert new rows after the given Excel row
number starting from 1 and number of rows. For example, create two rows
before row 3 in Sheet1:
err := f.InsertRows("Sheet1", 3, 2)
Use this method with caution, which will affect changes in references such
as formulas, charts, and so on. If there is any referenced value of the
worksheet, it will cause a file error when you open it. The excelize only
partially updates these references currently.
MergeCell provides a function to merge cells by given range reference and
sheet name. Merging cells only keeps the upper-left cell value, and
discards the other values. For example create a merged cell of D3:E9 on
Sheet1:
err := f.MergeCell("Sheet1", "D3", "E9")
If you create a merged cell that overlaps with another existing merged cell,
those merged cells that already exist will be removed. The cell references
tuple after merging in the following range will be: A1(x3,y1) D1(x2,y1)
A8(x3,y4) D8(x2,y4)
B1(x1,y1) D1(x2,y1) +------------------------+ | | A4(x3,y3) | C4(x4,y3) | +------------------------+ | | | | | | |B5(x1,y2) | D5(x2,y2)| | +------------------------+ | | |A8(x3,y4) C8(x4,y4)| +------------------------+
func (f *File) NewConditionalStyle(style *Style) (int, error)
NewConditionalStyle provides a function to create style for conditional
format by given style format. The parameters are the same with the NewStyle
function.
NewSheet provides the function to create a new sheet by given a worksheet
name and returns the index of the sheets in the workbook after it appended.
Note that when creating a new workbook, the default worksheet named
`Sheet1` will be created.
NewStreamWriter return stream writer struct by given worksheet name for
generate new worksheet with large amounts of data. Note that after set
rows, you must call the ‘Flush’ method to end the streaming writing process
and ensure that the order of row numbers is ascending, the normal mode
functions and stream mode functions can’t be work mixed to writing data on
the worksheets, you can’t get cell value when in-memory chunks data over
16MB. For example, set data for worksheet of size 102400 rows x 50 columns
with numbers and style:
f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() sw, err := f.NewStreamWriter("Sheet1") if err != nil { fmt.Println(err) return } styleID, err := f.NewStyle(&excelize.Style{Font: &excelize.Font{Color: "777777"}}) if err != nil { fmt.Println(err) return } if err := sw.SetRow("A1", []interface{}{ excelize.Cell{StyleID: styleID, Value: "Data"}, []excelize.RichTextRun{ {Text: "Rich ", Font: &excelize.Font{Color: "2354e8"}}, {Text: "Text", Font: &excelize.Font{Color: "e83723"}}, }, }, excelize.RowOpts{Height: 45, Hidden: false}); err != nil { fmt.Println(err) return } for rowID := 2; rowID <= 102400; rowID++ { row := make([]interface{}, 50) for colID := 0; colID < 50; colID++ { row[colID] = rand.Intn(640000) } cell, err := excelize.CoordinatesToCellName(1, rowID) if err != nil { fmt.Println(err) break } if err := sw.SetRow(cell, row); err != nil { fmt.Println(err) break } } if err := sw.Flush(); err != nil { fmt.Println(err) return } if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) }
Set cell value and cell formula for a worksheet with stream writer:
err := sw.SetRow("A1", []interface{}{ excelize.Cell{Value: 1}, excelize.Cell{Value: 2}, excelize.Cell{Formula: "SUM(A1,B1)"}});
Set cell value and rows style for a worksheet with stream writer:
err := sw.SetRow("A1", []interface{}{ excelize.Cell{Value: 1}}, excelize.RowOpts{StyleID: styleID, Height: 20, Hidden: false});
NewStyle provides a function to create the style for cells by given style
options. This function is concurrency safe. Note that the ‘Font.Color’ field
uses an RGB color represented in ‘RRGGBB’ hexadecimal notation.
The following table shows the border types used in ‘Border.Type’ supported by
excelize:
Type | Description --------------+------------------ left | Left border top | Top border right | Right border bottom | Bottom border diagonalDown | Diagonal down border diagonalUp | Diagonal up border
The following table shows the border styles used in ‘Border.Style’ supported
by excelize index number:
Index | Name | Weight | Style -------+---------------+--------+------------- 0 | None | 0 | 1 | Continuous | 1 | ----------- 2 | Continuous | 2 | ----------- 3 | Dash | 1 | - - - - - - 4 | Dot | 1 | . . . . . . 5 | Continuous | 3 | ----------- 6 | Double | 3 | =========== 7 | Continuous | 0 | ----------- 8 | Dash | 2 | - - - - - - 9 | Dash Dot | 1 | - . - . - . 10 | Dash Dot | 2 | - . - . - . 11 | Dash Dot Dot | 1 | - . . - . . 12 | Dash Dot Dot | 2 | - . . - . . 13 | SlantDash Dot | 2 | / - . / - .
The following table shows the border styles used in ‘Border.Style’ in the
order shown in the Excel dialog:
Index | Style | Index | Style -------+-------------+-------+------------- 0 | None | 12 | - . . - . . 7 | ----------- | 13 | / - . / - . 4 | . . . . . . | 10 | - . - . - . 11 | - . . - . . | 8 | - - - - - - 9 | - . - . - . | 2 | ----------- 3 | - - - - - - | 5 | ----------- 1 | ----------- | 6 | ===========
The following table shows the shading styles used in ‘Fill.Shading’ supported
by excelize index number:
Index | Style | Index | Style -------+-----------------+-------+----------------- 0-2 | Horizontal | 9-11 | Diagonal down 3-5 | Vertical | 12-15 | From corner 6-8 | Diagonal Up | 16 | From center
The following table shows the pattern styles used in ‘Fill.Pattern’ supported
by excelize index number:
Index | Style | Index | Style -------+-----------------+-------+----------------- 0 | None | 10 | darkTrellis 1 | solid | 11 | lightHorizontal 2 | mediumGray | 12 | lightVertical 3 | darkGray | 13 | lightDown 4 | lightGray | 14 | lightUp 5 | darkHorizontal | 15 | lightGrid 6 | darkVertical | 16 | lightTrellis 7 | darkDown | 17 | gray125 8 | darkUp | 18 | gray0625 9 | darkGrid | |
The following table shows the type of cells’ horizontal alignment used
in ‘Alignment.Horizontal’:
Style ------------------ left center right fill justify centerContinuous distributed
The following table shows the type of cells’ vertical alignment used in
‘Alignment.Vertical’:
Style ------------------ top center justify distributed
The following table shows the type of font underline style used in
‘Font.Underline’:
Style ------------------ none single double
Excel’s built-in all languages formats are shown in the following table:
Index | Format String -------+---------------------------------------------------- 0 | General 1 | 0 2 | 0.00 3 | #,##0 4 | #,##0.00 5 | ($#,##0_);($#,##0) 6 | ($#,##0_);[Red]($#,##0) 7 | ($#,##0.00_);($#,##0.00) 8 | ($#,##0.00_);[Red]($#,##0.00) 9 | 0% 10 | 0.00% 11 | 0.00E+00 12 | # ?/? 13 | # ??/?? 14 | m/d/yy 15 | d-mmm-yy 16 | d-mmm 17 | mmm-yy 18 | h:mm AM/PM 19 | h:mm:ss AM/PM 20 | h:mm 21 | h:mm:ss 22 | m/d/yy h:mm ... | ... 37 | (#,##0_);(#,##0) 38 | (#,##0_);[Red](#,##0) 39 | (#,##0.00_);(#,##0.00) 40 | (#,##0.00_);[Red](#,##0.00) 41 | _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_) 42 | _($* #,##0_);_($* (#,##0);_($* "-"_);_(@_) 43 | _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_) 44 | _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_) 45 | mm:ss 46 | [h]:mm:ss 47 | mm:ss.0 48 | ##0.0E+0 49 | @
Number format code in zh-tw language:
Index | Symbol -------+------------------------------------------- 27 | [$-404]e/m/d 28 | [$-404]e"年"m"月"d"日" 29 | [$-404]e"年"m"月"d"日" 30 | m/d/yy 31 | yyyy"年"m"月"d"日" 32 | hh"時"mm"分" 33 | hh"時"mm"分"ss"秒" 34 | 上午/下午 hh"時"mm"分" 35 | 上午/下午 hh"時"mm"分"ss"秒" 36 | [$-404]e/m/d 50 | [$-404]e/m/d 51 | [$-404]e"年"m"月"d"日" 52 | 上午/下午 hh"時"mm"分" 53 | 上午/下午 hh"時"mm"分"ss"秒" 54 | [$-404]e"年"m"月"d"日" 55 | 上午/下午 hh"時"mm"分" 56 | 上午/下午 hh"時"mm"分"ss"秒" 57 | [$-404]e/m/d 58 | [$-404]e"年"m"月"d"日"
Number format code in zh-cn language:
Index | Symbol -------+------------------------------------------- 27 | yyyy"年"m"月" 28 | m"月"d"日" 29 | m"月"d"日" 30 | m-d-yy 31 | yyyy"年"m"月"d"日" 32 | h"时"mm"分" 33 | h"时"mm"分"ss"秒" 34 | 上午/下午 h"时"mm"分" 35 | 上午/下午 h"时"mm"分"ss"秒 36 | yyyy"年"m"月 50 | yyyy"年"m"月 51 | m"月"d"日 52 | yyyy"年"m"月 53 | m"月"d"日 54 | m"月"d"日 55 | 上午/下午 h"时"mm"分 56 | 上午/下午 h"时"mm"分"ss"秒 57 | yyyy"年"m"月 58 | m"月"d"日"
Number format code with unicode values provided for language glyphs where
they occur in zh-tw language:
Index | Symbol -------+------------------------------------------- 27 | [$-404]e/m/ 28 | [$-404]e"5E74"m"6708"d"65E5 29 | [$-404]e"5E74"m"6708"d"65E5 30 | m/d/y 31 | yyyy"5E74"m"6708"d"65E5 32 | hh"6642"mm"5206 33 | hh"6642"mm"5206"ss"79D2 34 | 4E0A5348/4E0B5348hh"6642"mm"5206 35 | 4E0A5348/4E0B5348hh"6642"mm"5206"ss"79D2 36 | [$-404]e/m/ 50 | [$-404]e/m/ 51 | [$-404]e"5E74"m"6708"d"65E5 52 | 4E0A5348/4E0B5348hh"6642"mm"5206 53 | 4E0A5348/4E0B5348hh"6642"mm"5206"ss"79D2 54 | [$-404]e"5E74"m"6708"d"65E5 55 | 4E0A5348/4E0B5348hh"6642"mm"5206 56 | 4E0A5348/4E0B5348hh"6642"mm"5206"ss"79D2 57 | [$-404]e/m/ 58 | [$-404]e"5E74"m"6708"d"65E5"
Number format code with unicode values provided for language glyphs where
they occur in zh-cn language:
Index | Symbol -------+------------------------------------------- 27 | yyyy"5E74"m"6708 28 | m"6708"d"65E5 29 | m"6708"d"65E5 30 | m-d-y 31 | yyyy"5E74"m"6708"d"65E5 32 | h"65F6"mm"5206 33 | h"65F6"mm"5206"ss"79D2 34 | 4E0A5348/4E0B5348h"65F6"mm"5206 35 | 4E0A5348/4E0B5348h"65F6"mm"5206"ss"79D2 36 | yyyy"5E74"m"6708 50 | yyyy"5E74"m"6708 51 | m"6708"d"65E5 52 | yyyy"5E74"m"6708 53 | m"6708"d"65E5 54 | m"6708"d"65E5 55 | 4E0A5348/4E0B5348h"65F6"mm"5206 56 | 4E0A5348/4E0B5348h"65F6"mm"5206"ss"79D2 57 | yyyy"5E74"m"6708 58 | m"6708"d"65E5"
Number format code in ja-jp language:
Index | Symbol -------+------------------------------------------- 27 | [$-411]ge.m.d 28 | [$-411]ggge"年"m"月"d"日 29 | [$-411]ggge"年"m"月"d"日 30 | m/d/y 31 | yyyy"年"m"月"d"日 32 | h"時"mm"分 33 | h"時"mm"分"ss"秒 34 | yyyy"年"m"月 35 | m"月"d"日 36 | [$-411]ge.m.d 50 | [$-411]ge.m.d 51 | [$-411]ggge"年"m"月"d"日 52 | yyyy"年"m"月 53 | m"月"d"日 54 | [$-411]ggge"年"m"月"d"日 55 | yyyy"年"m"月 56 | m"月"d"日 57 | [$-411]ge.m.d 58 | [$-411]ggge"年"m"月"d"日"
Number format code in ko-kr language:
Index | Symbol -------+------------------------------------------- 27 | yyyy"年" mm"月" dd"日 28 | mm-d 29 | mm-d 30 | mm-dd-y 31 | yyyy"년" mm"월" dd"일 32 | h"시" mm"분 33 | h"시" mm"분" ss"초 34 | yyyy-mm-d 35 | yyyy-mm-d 36 | yyyy"年" mm"月" dd"日 50 | yyyy"年" mm"月" dd"日 51 | mm-d 52 | yyyy-mm-d 53 | yyyy-mm-d 54 | mm-d 55 | yyyy-mm-d 56 | yyyy-mm-d 57 | yyyy"年" mm"月" dd"日 58 | mm-dd
Number format code with unicode values provided for language glyphs where
they occur in ja-jp language:
Index | Symbol -------+------------------------------------------- 27 | [$-411]ge.m.d 28 | [$-411]ggge"5E74"m"6708"d"65E5 29 | [$-411]ggge"5E74"m"6708"d"65E5 30 | m/d/y 31 | yyyy"5E74"m"6708"d"65E5 32 | h"6642"mm"5206 33 | h"6642"mm"5206"ss"79D2 34 | yyyy"5E74"m"6708 35 | m"6708"d"65E5 36 | [$-411]ge.m.d 50 | [$-411]ge.m.d 51 | [$-411]ggge"5E74"m"6708"d"65E5 52 | yyyy"5E74"m"6708 53 | m"6708"d"65E5 54 | [$-411]ggge"5E74"m"6708"d"65E5 55 | yyyy"5E74"m"6708 56 | m"6708"d"65E5 57 | [$-411]ge.m.d 58 | [$-411]ggge"5E74"m"6708"d"65E5"
Number format code with unicode values provided for language glyphs where
they occur in ko-kr language:
Index | Symbol -------+------------------------------------------- 27 | yyyy"5E74" mm"6708" dd"65E5 28 | mm-d 29 | mm-d 30 | mm-dd-y 31 | yyyy"B144" mm"C6D4" dd"C77C 32 | h"C2DC" mm"BD84 33 | h"C2DC" mm"BD84" ss"CD08 34 | yyyy-mm-d 35 | yyyy-mm-d 36 | yyyy"5E74" mm"6708" dd"65E5 50 | yyyy"5E74" mm"6708" dd"65E5 51 | mm-d 52 | yyyy-mm-d 53 | yyyy-mm-d 54 | mm-d 55 | yyyy-mm-d 56 | yyyy-mm-d 57 | yyyy"5E74" mm"6708" dd"65E5 58 | mm-dd
Number format code in th-th language:
Index | Symbol -------+------------------------------------------- 59 | t 60 | t0.0 61 | t#,## 62 | t#,##0.0 67 | t0 68 | t0.00 69 | t# ?/ 70 | t# ??/? 71 | ว/ด/ปปป 72 | ว-ดดด-ป 73 | ว-ดด 74 | ดดด-ป 75 | ช:น 76 | ช:นน:ท 77 | ว/ด/ปปปป ช:น 78 | นน:ท 79 | [ช]:นน:ท 80 | นน:ทท. 81 | d/m/bb
Number format code with unicode values provided for language glyphs where
they occur in th-th language:
Index | Symbol -------+------------------------------------------- 59 | t 60 | t0.0 61 | t#,## 62 | t#,##0.0 67 | t0 68 | t0.00 69 | t# ?/ 70 | t# ??/? 71 | 0E27/0E14/0E1B0E1B0E1B0E1 72 | 0E27-0E140E140E14-0E1B0E1 73 | 0E27-0E140E140E1 74 | 0E140E140E14-0E1B0E1 75 | 0E0A:0E190E1 76 | 0E0A:0E190E19:0E170E1 77 | 0E27/0E14/0E1B0E1B0E1B0E1B 0E0A:0E190E1 78 | 0E190E19:0E170E1 79 | [0E0A]:0E190E19:0E170E1 80 | 0E190E19:0E170E17. 81 | d/m/bb
Excelize built-in currency formats are shown in the following table, only
support these types in the following table (Index number is used only for
markup and is not used inside an Excel file and you can’t get formatted value
by the function GetCellValue) currently:
Index | Symbol -------+--------------------------------------------------------------- 164 | ¥ 165 | $ English (United States) 166 | $ Cherokee (United States) 167 | $ Chinese (Singapore) 168 | $ Chinese (Taiwan) 169 | $ English (Australia) 170 | $ English (Belize) 171 | $ English (Canada) 172 | $ English (Jamaica) 173 | $ English (New Zealand) 174 | $ English (Singapore) 175 | $ English (Trinidad & Tobago) 176 | $ English (U.S. Virgin Islands) 177 | $ English (United States) 178 | $ French (Canada) 179 | $ Hawaiian (United States) 180 | $ Malay (Brunei) 181 | $ Quechua (Ecuador) 182 | $ Spanish (Chile) 183 | $ Spanish (Colombia) 184 | $ Spanish (Ecuador) 185 | $ Spanish (El Salvador) 186 | $ Spanish (Mexico) 187 | $ Spanish (Puerto Rico) 188 | $ Spanish (United States) 189 | $ Spanish (Uruguay) 190 | £ English (United Kingdom) 191 | £ Scottish Gaelic (United Kingdom) 192 | £ Welsh (United Kindom) 193 | ¥ Chinese (China) 194 | ¥ Japanese (Japan) 195 | ¥ Sichuan Yi (China) 196 | ¥ Tibetan (China) 197 | ¥ Uyghur (China) 198 | ֏ Armenian (Armenia) 199 | ؋ Pashto (Afghanistan) 200 | ؋ Persian (Afghanistan) 201 | ৳ Bengali (Bangladesh) 202 | ៛ Khmer (Cambodia) 203 | ₡ Spanish (Costa Rica) 204 | ₦ Hausa (Nigeria) 205 | ₦ Igbo (Nigeria) 206 | ₩ Korean (South Korea) 207 | ₪ Hebrew (Israel) 208 | ₫ Vietnamese (Vietnam) 209 | € Basque (Spain) 210 | € Breton (France) 211 | € Catalan (Spain) 212 | € Corsican (France) 213 | € Dutch (Belgium) 214 | € Dutch (Netherlands) 215 | € English (Ireland) 216 | € Estonian (Estonia) 217 | € Euro (€ 123) 218 | € Euro (123 €) 219 | € Finnish (Finland) 220 | € French (Belgium) 221 | € French (France) 222 | € French (Luxembourg) 223 | € French (Monaco) 224 | € French (Réunion) 225 | € Galician (Spain) 226 | € German (Austria) 227 | € German (German) 228 | € German (Luxembourg) 229 | € Greek (Greece) 230 | € Inari Sami (Finland) 231 | € Irish (Ireland) 232 | € Italian (Italy) 233 | € Latin (Italy) 234 | € Latin, Serbian (Montenegro) 235 | € Larvian (Latvia) 236 | € Lithuanian (Lithuania) 237 | € Lower Sorbian (Germany) 238 | € Luxembourgish (Luxembourg) 239 | € Maltese (Malta) 240 | € Northern Sami (Finland) 241 | € Occitan (France) 242 | € Portuguese (Portugal) 243 | € Serbian (Montenegro) 244 | € Skolt Sami (Finland) 245 | € Slovak (Slovakia) 246 | € Slovenian (Slovenia) 247 | € Spanish (Spain) 248 | € Swedish (Finland) 249 | € Swiss German (France) 250 | € Upper Sorbian (Germany) 251 | € Western Frisian (Netherlands) 252 | ₭ Lao (Laos) 253 | ₮ Mongolian (Mongolia) 254 | ₮ Mongolian, Mongolian (Mongolia) 255 | ₱ English (Philippines) 256 | ₱ Filipino (Philippines) 257 | ₴ Ukrainian (Ukraine) 258 | ₸ Kazakh (Kazakhstan) 259 | ₹ Arabic, Kashmiri (India) 260 | ₹ English (India) 261 | ₹ Gujarati (India) 262 | ₹ Hindi (India) 263 | ₹ Kannada (India) 264 | ₹ Kashmiri (India) 265 | ₹ Konkani (India) 266 | ₹ Manipuri (India) 267 | ₹ Marathi (India) 268 | ₹ Nepali (India) 269 | ₹ Oriya (India) 270 | ₹ Punjabi (India) 271 | ₹ Sanskrit (India) 272 | ₹ Sindhi (India) 273 | ₹ Tamil (India) 274 | ₹ Urdu (India) 275 | ₺ Turkish (Turkey) 276 | ₼ Azerbaijani (Azerbaijan) 277 | ₼ Cyrillic, Azerbaijani (Azerbaijan) 278 | ₽ Russian (Russia) 279 | ₽ Sakha (Russia) 280 | ₾ Georgian (Georgia) 281 | B/. Spanish (Panama) 282 | Br Oromo (Ethiopia) 283 | Br Somali (Ethiopia) 284 | Br Tigrinya (Ethiopia) 285 | Bs Quechua (Bolivia) 286 | Bs Spanish (Bolivia) 287 | BS. Spanish (Venezuela) 288 | BWP Tswana (Botswana) 289 | C$ Spanish (Nicaragua) 290 | CA$ Latin, Inuktitut (Canada) 291 | CA$ Mohawk (Canada) 292 | CA$ Unified Canadian Aboriginal Syllabics, Inuktitut (Canada) 293 | CFA French (Mali) 294 | CFA French (Senegal) 295 | CFA Fulah (Senegal) 296 | CFA Wolof (Senegal) 297 | CHF French (Switzerland) 298 | CHF German (Liechtenstein) 299 | CHF German (Switzerland) 300 | CHF Italian (Switzerland) 301 | CHF Romansh (Switzerland) 302 | CLP Mapuche (Chile) 303 | CN¥ Mongolian, Mongolian (China) 304 | DZD Central Atlas Tamazight (Algeria) 305 | FCFA French (Cameroon) 306 | Ft Hungarian (Hungary) 307 | G French (Haiti) 308 | Gs. Spanish (Paraguay) 309 | GTQ K'iche' (Guatemala) 310 | HK$ Chinese (Hong Kong (China)) 311 | HK$ English (Hong Kong (China)) 312 | HRK Croatian (Croatia) 313 | IDR English (Indonesia) 314 | IQD Arbic, Central Kurdish (Iraq) 315 | ISK Icelandic (Iceland) 316 | K Burmese (Myanmar (Burma)) 317 | Kč Czech (Czech Republic) 318 | KM Bosnian (Bosnia & Herzegovina) 319 | KM Croatian (Bosnia & Herzegovina) 320 | KM Latin, Serbian (Bosnia & Herzegovina) 321 | kr Faroese (Faroe Islands) 322 | kr Northern Sami (Norway) 323 | kr Northern Sami (Sweden) 324 | kr Norwegian Bokmål (Norway) 325 | kr Norwegian Nynorsk (Norway) 326 | kr Swedish (Sweden) 327 | kr. Danish (Denmark) 328 | kr. Kalaallisut (Greenland) 329 | Ksh Swahili (kenya) 330 | L Romanian (Moldova) 331 | L Russian (Moldova) 332 | L Spanish (Honduras) 333 | Lekë Albanian (Albania) 334 | MAD Arabic, Central Atlas Tamazight (Morocco) 335 | MAD French (Morocco) 336 | MAD Tifinagh, Central Atlas Tamazight (Morocco) 337 | MOP$ Chinese (Macau (China)) 338 | MVR Divehi (Maldives) 339 | Nfk Tigrinya (Eritrea) 340 | NGN Bini (Nigeria) 341 | NGN Fulah (Nigeria) 342 | NGN Ibibio (Nigeria) 343 | NGN Kanuri (Nigeria) 344 | NOK Lule Sami (Norway) 345 | NOK Southern Sami (Norway) 346 | NZ$ Maori (New Zealand) 347 | PKR Sindhi (Pakistan) 348 | PYG Guarani (Paraguay) 349 | Q Spanish (Guatemala) 350 | R Afrikaans (South Africa) 351 | R English (South Africa) 352 | R Zulu (South Africa) 353 | R$ Portuguese (Brazil) 354 | RD$ Spanish (Dominican Republic) 355 | RF Kinyarwanda (Rwanda) 356 | RM English (Malaysia) 357 | RM Malay (Malaysia) 358 | RON Romanian (Romania) 359 | Rp Indonesoan (Indonesia) 360 | Rs Urdu (Pakistan) 361 | Rs. Tamil (Sri Lanka) 362 | RSD Latin, Serbian (Serbia) 363 | RSD Serbian (Serbia) 364 | RUB Bashkir (Russia) 365 | RUB Tatar (Russia) 366 | S/. Quechua (Peru) 367 | S/. Spanish (Peru) 368 | SEK Lule Sami (Sweden) 369 | SEK Southern Sami (Sweden) 370 | soʻm Latin, Uzbek (Uzbekistan) 371 | soʻm Uzbek (Uzbekistan) 372 | SYP Syriac (Syria) 373 | THB Thai (Thailand) 374 | TMT Turkmen (Turkmenistan) 375 | US$ English (Zimbabwe) 376 | ZAR Northern Sotho (South Africa) 377 | ZAR Southern Sotho (South Africa) 378 | ZAR Tsonga (South Africa) 379 | ZAR Tswana (south Africa) 380 | ZAR Venda (South Africa) 381 | ZAR Xhosa (South Africa) 382 | zł Polish (Poland) 383 | ден Macedonian (Macedonia) 384 | KM Cyrillic, Bosnian (Bosnia & Herzegovina) 385 | KM Serbian (Bosnia & Herzegovina) 386 | лв. Bulgarian (Bulgaria) 387 | p. Belarusian (Belarus) 388 | сом Kyrgyz (Kyrgyzstan) 389 | сом Tajik (Tajikistan) 390 | ج.م. Arabic (Egypt) 391 | د.أ. Arabic (Jordan) 392 | د.أ. Arabic (United Arab Emirates) 393 | د.ب. Arabic (Bahrain) 394 | د.ت. Arabic (Tunisia) 395 | د.ج. Arabic (Algeria) 396 | د.ع. Arabic (Iraq) 397 | د.ك. Arabic (Kuwait) 398 | د.ل. Arabic (Libya) 399 | د.م. Arabic (Morocco) 400 | ر Punjabi (Pakistan) 401 | ر.س. Arabic (Saudi Arabia) 402 | ر.ع. Arabic (Oman) 403 | ر.ق. Arabic (Qatar) 404 | ر.ي. Arabic (Yemen) 405 | ریال Persian (Iran) 406 | ل.س. Arabic (Syria) 407 | ل.ل. Arabic (Lebanon) 408 | ብር Amharic (Ethiopia) 409 | रू Nepaol (Nepal) 410 | රු. Sinhala (Sri Lanka) 411 | ADP 412 | AED 413 | AFA 414 | AFN 415 | ALL 416 | AMD 417 | ANG 418 | AOA 419 | ARS 420 | ATS 421 | AUD 422 | AWG 423 | AZM 424 | AZN 425 | BAM 426 | BBD 427 | BDT 428 | BEF 429 | BGL 430 | BGN 431 | BHD 432 | BIF 433 | BMD 434 | BND 435 | BOB 436 | BOV 437 | BRL 438 | BSD 439 | BTN 440 | BWP 441 | BYR 442 | BZD 443 | CAD 444 | CDF 445 | CHE 446 | CHF 447 | CHW 448 | CLF 449 | CLP 450 | CNY 451 | COP 452 | COU 453 | CRC 454 | CSD 455 | CUC 456 | CVE 457 | CYP 458 | CZK 459 | DEM 460 | DJF 461 | DKK 462 | DOP 463 | DZD 464 | ECS 465 | ECV 466 | EEK 467 | EGP 468 | ERN 469 | ESP 470 | ETB 471 | EUR 472 | FIM 473 | FJD 474 | FKP 475 | FRF 476 | GBP 477 | GEL 478 | GHC 479 | GHS 480 | GIP 481 | GMD 482 | GNF 483 | GRD 484 | GTQ 485 | GYD 486 | HKD 487 | HNL 488 | HRK 489 | HTG 490 | HUF 491 | IDR 492 | IEP 493 | ILS 494 | INR 495 | IQD 496 | IRR 497 | ISK 498 | ITL 499 | JMD 500 | JOD 501 | JPY 502 | KAF 503 | KES 504 | KGS 505 | KHR 506 | KMF 507 | KPW 508 | KRW 509 | KWD 510 | KYD 511 | KZT 512 | LAK 513 | LBP 514 | LKR 515 | LRD 516 | LSL 517 | LTL 518 | LUF 519 | LVL 520 | LYD 521 | MAD 522 | MDL 523 | MGA 524 | MGF 525 | MKD 526 | MMK 527 | MNT 528 | MOP 529 | MRO 530 | MTL 531 | MUR 532 | MVR 533 | MWK 534 | MXN 535 | MXV 536 | MYR 537 | MZM 538 | MZN 539 | NAD 540 | NGN 541 | NIO 542 | NLG 543 | NOK 544 | NPR 545 | NTD 546 | NZD 547 | OMR 548 | PAB 549 | PEN 550 | PGK 551 | PHP 552 | PKR 553 | PLN 554 | PTE 555 | PYG 556 | QAR 557 | ROL 558 | RON 559 | RSD 560 | RUB 561 | RUR 562 | RWF 563 | SAR 564 | SBD 565 | SCR 566 | SDD 567 | SDG 568 | SDP 569 | SEK 570 | SGD 571 | SHP 572 | SIT 573 | SKK 574 | SLL 575 | SOS 576 | SPL 577 | SRD 578 | SRG 579 | STD 580 | SVC 581 | SYP 582 | SZL 583 | THB 584 | TJR 585 | TJS 586 | TMM 587 | TMT 588 | TND 589 | TOP 590 | TRL 591 | TRY 592 | TTD 593 | TWD 594 | TZS 595 | UAH 596 | UGX 597 | USD 598 | USN 599 | USS 600 | UYI 601 | UYU 602 | UZS 603 | VEB 604 | VEF 605 | VND 606 | VUV 607 | WST 608 | XAF 609 | XAG 610 | XAU 611 | XB5 612 | XBA 613 | XBB 614 | XBC 615 | XBD 616 | XCD 617 | XDR 618 | XFO 619 | XFU 620 | XOF 621 | XPD 622 | XPF 623 | XPT 624 | XTS 625 | XXX 626 | YER 627 | YUM 628 | ZAR 629 | ZMK 630 | ZMW 631 | ZWD 632 | ZWL 633 | ZWN 634 | ZWR
Excelize support set custom number format for cell. For example, set number
as date type in Uruguay (Spanish) format for Sheet1!A6:
f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() if err := f.SetCellValue("Sheet1", "A6", 42920.5); err != nil { fmt.Println(err) return } exp := "[$-380A]dddd\,\ dd" de "mmmm" de "yyyy;@" style, err := f.NewStyle(&excelize.Style{CustomNumFmt: &exp}) if err != nil { fmt.Println(err) return } err = f.SetCellStyle("Sheet1", "A6", "A6", style)
Cell Sheet1!A6 in the Excel Application: martes, 04 de Julio de 2017
ProtectSheet provides a function to prevent other users from accidentally or
deliberately changing, moving, or deleting data in a worksheet. The
optional field AlgorithmName specified hash algorithm, support XOR, MD4,
MD5, SHA-1, SHA2-56, SHA-384, and SHA-512 currently, if no hash algorithm
specified, will be using the XOR algorithm as default. For example, protect
Sheet1 with protection settings:
err := f.ProtectSheet("Sheet1", &excelize.SheetProtectionOptions{ AlgorithmName: "SHA-512", Password: "password", SelectLockedCells: true, SelectUnlockedCells: true, EditScenarios: true, })
func (f *File) ProtectWorkbook(opts *WorkbookProtectionOptions) error
ProtectWorkbook provides a function to prevent other users from viewing
hidden worksheets, adding, moving, deleting, or hiding worksheets, and
renaming worksheets in a workbook. The optional field AlgorithmName
specified hash algorithm, support XOR, MD4, MD5, SHA-1, SHA2-56, SHA-384,
and SHA-512 currently, if no hash algorithm specified, will be using the XOR
algorithm as default. The generated workbook only works on Microsoft Office
2007 and later. For example, protect workbook with protection settings:
err := f.ProtectWorkbook(&excelize.WorkbookProtectionOptions{ Password: "password", LockStructure: true, })
ReadZipReader extract spreadsheet with given options.
RemoveCol provides a function to remove single column by given worksheet
name and column index. For example, remove column C in Sheet1:
err := f.RemoveCol("Sheet1", "C")
Use this method with caution, which will affect changes in references such
as formulas, charts, and so on. If there is any referenced value of the
worksheet, it will cause a file error when you open it. The excelize only
partially updates these references currently.
RemovePageBreak remove a page break by given worksheet name and cell
reference.
RemoveRow provides a function to remove single row by given worksheet name
and Excel row number. For example, remove row 3 in Sheet1:
err := f.RemoveRow("Sheet1", 3)
Use this method with caution, which will affect changes in references such
as formulas, charts, and so on. If there is any referenced value of the
worksheet, it will cause a file error when you open it. The excelize only
partially updates these references currently.
Rows returns a rows iterator, used for streaming reading data for a
worksheet with a large data. This function is concurrency safe. For
example:
rows, err := f.Rows("Sheet1") if err != nil { fmt.Println(err) return } for rows.Next() { row, err := rows.Columns() if err != nil { fmt.Println(err) } for _, colCell := range row { fmt.Print(colCell, "t") } fmt.Println() } if err = rows.Close(); err != nil { fmt.Println(err) }
func (f *File) Save(opts ...Options) error
Save provides a function to override the spreadsheet with origin path.
SaveAs provides a function to create or update to a spreadsheet at the
provided path.
SearchSheet provides a function to get cell reference by given worksheet name,
cell value, and regular expression. The function doesn’t support searching
on the calculated result, formatted numbers and conditional lookup
currently. If it is a merged cell, it will return the cell reference of the
upper left cell of the merged range reference.
An example of search the cell reference of the value of «100» on Sheet1:
result, err := f.SearchSheet("Sheet1", "100")
An example of search the cell reference where the numerical value in the range
of «0-9» of Sheet1 is described:
result, err := f.SearchSheet("Sheet1", "[0-9]", true)
func (f *File) SetActiveSheet(index int)
SetActiveSheet provides a function to set the default active sheet of the
workbook by a given index. Note that the active index is different from the
ID returned by function GetSheetMap(). It should be greater than or equal to 0
and less than the total worksheet numbers.
func (f *File) SetAppProps(appProperties *AppProperties) error
SetAppProps provides a function to set document application properties. The
properties that can be set are:
Property | Description -------------------+-------------------------------------------------------------------------- Application | The name of the application that created this document. | ScaleCrop | Indicates the display mode of the document thumbnail. Set this element | to 'true' to enable scaling of the document thumbnail to the display. Set | this element to 'false' to enable cropping of the document thumbnail to | show only sections that will fit the display. | DocSecurity | Security level of a document as a numeric value. Document security is | defined as: | 1 - Document is password protected. | 2 - Document is recommended to be opened as read-only. | 3 - Document is enforced to be opened as read-only. | 4 - Document is locked for annotation. | Company | The name of a company associated with the document. | LinksUpToDate | Indicates whether hyperlinks in a document are up-to-date. Set this | element to 'true' to indicate that hyperlinks are updated. Set this | element to 'false' to indicate that hyperlinks are outdated. | HyperlinksChanged | Specifies that one or more hyperlinks in this part were updated | exclusively in this part by a producer. The next producer to open this | document shall update the hyperlink relationships with the new | hyperlinks specified in this part. | AppVersion | Specifies the version of the application which produced this document. | The content of this element shall be of the form XX.YYYY where X and Y | represent numerical values, or the document shall be considered | non-conformant.
For example:
err := f.SetAppProps(&excelize.AppProperties{ Application: "Microsoft Excel", ScaleCrop: true, DocSecurity: 3, Company: "Company Name", LinksUpToDate: true, HyperlinksChanged: true, AppVersion: "16.0000", })
SetCellBool provides a function to set bool type value of a cell by given
worksheet name, cell reference and cell value.
func (f *File) SetCellDefault(sheet, cell, value string) error
SetCellDefault provides a function to set string type value of a cell as
default format without escaping the cell.
SetCellFloat sets a floating point value into a cell. The precision
parameter specifies how many places after the decimal will be shown
while -1 is a special value that will use as many decimal places as
necessary to represent the number. bitSize is 32 or 64 depending on if a
float32 or float64 was originally used for the value. For Example:
var x float32 = 1.325 f.SetCellFloat("Sheet1", "A1", float64(x), 2, 32)
f := NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() x := 3.14159265 if err := f.SetCellFloat("Sheet1", "A1", x, 2, 64); err != nil { fmt.Println(err) } val, err := f.GetCellValue("Sheet1", "A1") if err != nil { fmt.Println(err) return } fmt.Println(val)
Output: 3.14
func (f *File) SetCellFormula(sheet, cell, formula string, opts ...FormulaOpts) error
SetCellFormula provides a function to set formula on the cell is taken
according to the given worksheet name and cell formula settings. The result
of the formula cell can be calculated when the worksheet is opened by the
Office Excel application or can be using the «CalcCellValue» function also
can get the calculated cell value. If the Excel application doesn’t
calculate the formula automatically when the workbook has been opened,
please call «UpdateLinkedValue» after setting the cell formula functions.
Example 1, set normal formula «=SUM(A1,B1)» for the cell «A3» on «Sheet1»:
err := f.SetCellFormula("Sheet1", "A3", "=SUM(A1,B1)")
Example 2, set one-dimensional vertical constant array (column array) formula
«1,2,3» for the cell «A3» on «Sheet1»:
err := f.SetCellFormula("Sheet1", "A3", "={1;2;3}")
Example 3, set one-dimensional horizontal constant array (row array)
formula ‘»a»,»b»,»c»‘ for the cell «A3» on «Sheet1»:
err := f.SetCellFormula("Sheet1", "A3", "={"a","b","c"}")
Example 4, set two-dimensional constant array formula ‘{1,2,»a»,»b»}’ for
the cell «A3» on «Sheet1»:
formulaType, ref := excelize.STCellFormulaTypeArray, "A3:A3" err := f.SetCellFormula("Sheet1", "A3", "={1,2;"a","b"}", excelize.FormulaOpts{Ref: &ref, Type: &formulaType})
Example 5, set range array formula «A1:A2» for the cell «A3» on «Sheet1»:
formulaType, ref := excelize.STCellFormulaTypeArray, "A3:A3" err := f.SetCellFormula("Sheet1", "A3", "=A1:A2", excelize.FormulaOpts{Ref: &ref, Type: &formulaType})
Example 6, set shared formula «=A1+B1» for the cell «C1:C5»
on «Sheet1», «C1» is the master cell:
formulaType, ref := excelize.STCellFormulaTypeShared, "C1:C5" err := f.SetCellFormula("Sheet1", "C1", "=A1+B1", excelize.FormulaOpts{Ref: &ref, Type: &formulaType})
Example 7, set table formula «=SUM(Table1[[A]:[B]])» for the cell «C2»
on «Sheet1»:
package main import ( "fmt" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() for idx, row := range [][]interface{}{{"A", "B", "C"}, {1, 2}} { if err := f.SetSheetRow("Sheet1", fmt.Sprintf("A%d", idx+1), &row); err != nil { fmt.Println(err) return } } if err := f.AddTable("Sheet1", &excelize.Table{ Range: "A1:C2", Name: "Table1", StyleName: "TableStyleMedium2", }); err != nil { fmt.Println(err) return } formulaType := excelize.STCellFormulaTypeDataTable if err := f.SetCellFormula("Sheet1", "C2", "=SUM(Table1[[A]:[B]])", excelize.FormulaOpts{Type: &formulaType}); err != nil { fmt.Println(err) return } if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
func (f *File) SetCellHyperLink(sheet, cell, link, linkType string, opts ...HyperlinkOpts) error
SetCellHyperLink provides a function to set cell hyperlink by given
worksheet name and link URL address. LinkType defines two types of
hyperlink «External» for website or «Location» for moving to one of cell in
this workbook. Maximum limit hyperlinks in a worksheet is 65530. This
function is only used to set the hyperlink of the cell and doesn’t affect
the value of the cell. If you need to set the value of the cell, please use
the other functions such as `SetCellStyle` or `SetSheetRow`. The below is
example for external link.
display, tooltip := "https://github.com/xuri/excelize", "Excelize on GitHub" if err := f.SetCellHyperLink("Sheet1", "A3", display, "External", excelize.HyperlinkOpts{ Display: &display, Tooltip: &tooltip, }); err != nil { fmt.Println(err) } // Set underline and font color style for the cell. style, err := f.NewStyle(&excelize.Style{ Font: &excelize.Font{Color: "1265BE", Underline: "single"}, }) if err != nil { fmt.Println(err) } err = f.SetCellStyle("Sheet1", "A3", "A3", style)
This is another example for «Location»:
err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
SetCellInt provides a function to set int type value of a cell by given
worksheet name, cell reference and cell value.
SetCellRichText provides a function to set cell with rich text by given
worksheet. For example, set rich text on the A1 cell of the worksheet named
Sheet1:
package main import ( "fmt" "github.com/xuri/excelize/v2" ) func main() { f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() if err := f.SetRowHeight("Sheet1", 1, 35); err != nil { fmt.Println(err) return } if err := f.SetColWidth("Sheet1", "A", "A", 44); err != nil { fmt.Println(err) return } if err := f.SetCellRichText("Sheet1", "A1", []excelize.RichTextRun{ { Text: "bold", Font: &excelize.Font{ Bold: true, Color: "2354e8", Family: "Times New Roman", }, }, { Text: " and ", Font: &excelize.Font{ Family: "Times New Roman", }, }, { Text: "italic ", Font: &excelize.Font{ Bold: true, Color: "e83723", Italic: true, Family: "Times New Roman", }, }, { Text: "text with color and font-family,", Font: &excelize.Font{ Bold: true, Color: "2354e8", Family: "Times New Roman", }, }, { Text: "rnlarge text with ", Font: &excelize.Font{ Size: 14, Color: "ad23e8", }, }, { Text: "strike", Font: &excelize.Font{ Color: "e89923", Strike: true, }, }, { Text: " superscript", Font: &excelize.Font{ Color: "dbc21f", VertAlign: "superscript", }, }, { Text: " and ", Font: &excelize.Font{ Size: 14, Color: "ad23e8", VertAlign: "baseline", }, }, { Text: "underline", Font: &excelize.Font{ Color: "23e833", Underline: "single", }, }, { Text: " subscript.", Font: &excelize.Font{ Color: "017505", VertAlign: "subscript", }, }, }); err != nil { fmt.Println(err) return } style, err := f.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ WrapText: true, }, }) if err != nil { fmt.Println(err) return } if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil { fmt.Println(err) return } if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
SetCellStr provides a function to set string type value of a cell. Total
number of characters that a cell can contain 32767 characters.
SetCellStyle provides a function to add style attribute for cells by given
worksheet name, range reference and style ID. This function is concurrency
safe. Note that diagonalDown and diagonalUp type border should be use same
color in the same range. SetCellStyle will overwrite the existing
styles for the cell, it won’t append or merge style with existing styles.
For example create a borders of cell H9 on Sheet1:
style, err := f.NewStyle(&excelize.Style{ Border: []excelize.Border{ {Type: "left", Color: "0000FF", Style: 3}, {Type: "top", Color: "00FF00", Style: 4}, {Type: "bottom", Color: "FFFF00", Style: 5}, {Type: "right", Color: "FF0000", Style: 6}, {Type: "diagonalDown", Color: "A020F0", Style: 7}, {Type: "diagonalUp", Color: "A020F0", Style: 8}, }, }) if err != nil { fmt.Println(err) } err = f.SetCellStyle("Sheet1", "H9", "H9", style)
Set gradient fill with vertical variants shading styles for cell H9 on
Sheet1:
style, err := f.NewStyle(&excelize.Style{ Fill: excelize.Fill{Type: "gradient", Color: []string{"FFFFFF", "E0EBF5"}, Shading: 1}, }) if err != nil { fmt.Println(err) } err = f.SetCellStyle("Sheet1", "H9", "H9", style)
Set solid style pattern fill for cell H9 on Sheet1:
style, err := f.NewStyle(&excelize.Style{ Fill: excelize.Fill{Type: "pattern", Color: []string{"E0EBF5"}, Pattern: 1}, }) if err != nil { fmt.Println(err) } err = f.SetCellStyle("Sheet1", "H9", "H9", style)
Set alignment style for cell H9 on Sheet1:
style, err := f.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", Indent: 1, JustifyLastLine: true, ReadingOrder: 0, RelativeIndent: 1, ShrinkToFit: true, TextRotation: 45, Vertical: "", WrapText: true, }, }) if err != nil { fmt.Println(err) } err = f.SetCellStyle("Sheet1", "H9", "H9", style)
Dates and times in Excel are represented by real numbers, for example «Apr 7
2017 12:00 PM» is represented by the number 42920.5. Set date and time format
for cell H9 on Sheet1:
f.SetCellValue("Sheet1", "H9", 42920.5) style, err := f.NewStyle(&excelize.Style{NumFmt: 22}) if err != nil { fmt.Println(err) } err = f.SetCellStyle("Sheet1", "H9", "H9", style)
Set font style for cell H9 on Sheet1:
style, err := f.NewStyle(&excelize.Style{ Font: &excelize.Font{ Bold: true, Italic: true, Family: "Times New Roman", Size: 36, Color: "777777", }, }) if err != nil { fmt.Println(err) } err = f.SetCellStyle("Sheet1", "H9", "H9", style)
Hide and lock for cell H9 on Sheet1:
style, err := f.NewStyle(&excelize.Style{ Protection: &excelize.Protection{ Hidden: true, Locked: true, }, }) if err != nil { fmt.Println(err) } err = f.SetCellStyle("Sheet1", "H9", "H9", style)
func (f *File) SetCellValue(sheet, cell string, value interface{}) error
SetCellValue provides a function to set the value of a cell. This function
is concurrency safe. The specified coordinates should not be in the first
row of the table, a complex number can be set with string text. The
following shows the supported data types:
int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 float32 float64 string []byte time.Duration time.Time bool nil
Note that default date format is m/d/yy h:mm of time.Time type value. You
can set numbers format by the SetCellStyle function. If you need to set the
specialized date in Excel like January 0, 1900 or February 29, 1900, these
times can not representation in Go language time.Time data type. Please set
the cell value as number 0 or 60, then create and bind the date-time number
format style for the cell.
SetColOutlineLevel provides a function to set outline level of a single
column by given worksheet name and column name. The value of parameter
‘level’ is 1-7. For example, set outline level of column D in Sheet1 to 2:
err := f.SetColOutlineLevel("Sheet1", "D", 2)
SetColStyle provides a function to set style of columns by given worksheet
name, columns range and style ID. This function is concurrency safe. Note
that this will overwrite the existing styles for the columns, it won’t
append or merge style with existing styles.
For example set style of column H on Sheet1:
err = f.SetColStyle("Sheet1", "H", style)
Set style of columns C:F on Sheet1:
err = f.SetColStyle("Sheet1", "C:F", style)
SetColVisible provides a function to set visible columns by given worksheet
name, columns range and visibility. This function is concurrency safe.
For example hide column D on Sheet1:
err := f.SetColVisible("Sheet1", "D", false)
Hide the columns from D to F (included):
err := f.SetColVisible("Sheet1", "D:F", false)
SetColWidth provides a function to set the width of a single column or
multiple columns. This function is concurrency safe. For example:
err := f.SetColWidth("Sheet1", "A", "H", 20)
func (f *File) SetConditionalFormat(sheet, rangeRef string, opts []ConditionalFormatOptions) error
SetConditionalFormat provides a function to create conditional formatting
rule for cell value. Conditional formatting is a feature of Excel which
allows you to apply a format to a cell or a range of cells based on certain
criteria.
The type option is a required parameter and it has no default value.
Allowable type values and their associated parameters are:
Type | Parameters ---------------+------------------------------------ cell | Criteria | Value | MinValue | MaxValue date | Criteria | Value | MinValue | MaxValue time_period | Criteria text | Criteria | Value average | Criteria duplicate | (none) unique | (none) top | Criteria | Value bottom | Criteria | Value blanks | (none) no_blanks | (none) errors | (none) no_errors | (none) 2_color_scale | MinType | MaxType | MinValue | MaxValue | MinColor | MaxColor 3_color_scale | MinType | MidType | MaxType | MinValue | MidValue | MaxValue | MinColor | MidColor | MaxColor data_bar | MinType | MaxType | MinValue | MaxValue | BarBorderColor | BarColor | BarDirection | BarOnly | BarSolid icon_set | IconStyle | ReverseIcons | IconsOnly formula | Criteria
The ‘Criteria’ parameter is used to set the criteria by which the cell data
will be evaluated. It has no default value. The most common criteria as
applied to {«type»:»cell»} are:
between | not between | equal to | == not equal to | != greater than | > less than | < greater than or equal to | >= less than or equal to | <=
You can either use Excel’s textual description strings, in the first column
above, or the more common symbolic alternatives.
Additional criteria which are specific to other conditional format types are
shown in the relevant sections below.
value: The value is generally used along with the criteria parameter to set
the rule by which the cell data will be evaluated:
err := f.SetConditionalFormat("Sheet1", "D1:D10", []excelize.ConditionalFormatOptions{ { Type: "cell", Criteria: ">", Format: format, Value: "6", }, }, )
The value property can also be an cell reference:
err := f.SetConditionalFormat("Sheet1", "D1:D10", []excelize.ConditionalFormatOptions{ { Type: "cell", Criteria: ">", Format: format, Value: "$C$1", }, }, )
type: format — The format parameter is used to specify the format that will
be applied to the cell when the conditional formatting criterion is met. The
format is created using the NewConditionalStyle function in the same way as
cell formats:
format, err := f.NewConditionalStyle( &excelize.Style{ Font: &excelize.Font{Color: "9A0511"}, Fill: excelize.Fill{ Type: "pattern", Color: []string{"FEC7CE"}, Pattern: 1, }, }, ) if err != nil { fmt.Println(err) } err = f.SetConditionalFormat("Sheet1", "D1:D10", []excelize.ConditionalFormatOptions{ {Type: "cell", Criteria: ">", Format: format, Value: "6"}, }, )
Note: In Excel, a conditional format is superimposed over the existing cell
format and not all cell format properties can be modified. Properties that
cannot be modified in a conditional format are font name, font size,
superscript and subscript, diagonal borders, all alignment properties and all
protection properties.
Excel specifies some default formats to be used with conditional formatting.
These can be replicated using the following excelize formats:
// Rose format for bad conditional. format1, err := f.NewConditionalStyle( &excelize.Style{ Font: &excelize.Font{Color: "9A0511"}, Fill: excelize.Fill{ Type: "pattern", Color: []string{"#FEC7CE"}, Pattern: 1, }, }, ) // Light yellow format for neutral conditional. format2, err := f.NewConditionalStyle( &excelize.Style{ Font: &excelize.Font{Color: "9B5713"}, Fill: excelize.Fill{ Type: "pattern", Color: []string{"FEEAA0"}, Pattern: 1, }, }, ) // Light green format for good conditional. format3, err := f.NewConditionalStyle( &excelize.Style{ Font: &excelize.Font{Color: "09600B"}, Fill: excelize.Fill{ Type: "pattern", Color: []string{"C7EECF"}, Pattern: 1, }, }, )
type: MinValue — The ‘MinValue’ parameter is used to set the lower limiting
value when the criteria is either «between» or «not between».
// Highlight cells rules: between... err := f.SetConditionalFormat("Sheet1", "A1:A10", []excelize.ConditionalFormatOptions{ { Type: "cell", Criteria: "between", Format: format, MinValue: 6", MaxValue: 8", }, }, )
type: MaxValue — The ‘MaxValue’ parameter is used to set the upper limiting
value when the criteria is either «between» or «not between». See the
previous example.
type: average — The average type is used to specify Excel’s «Average» style
conditional format:
// Top/Bottom rules: Above Average... err := f.SetConditionalFormat("Sheet1", "A1:A10", []excelize.ConditionalFormatOptions{ { Type: "average", Criteria: "=", Format: format1, AboveAverage: true, }, }, ) // Top/Bottom rules: Below Average... err := f.SetConditionalFormat("Sheet1", "B1:B10", []excelize.ConditionalFormatOptions{ { Type: "average", Criteria: "=", Format: format2, AboveAverage: false, }, }, )
type: duplicate — The duplicate type is used to highlight duplicate cells in
a range:
// Highlight cells rules: Duplicate Values... err := f.SetConditionalFormat("Sheet1", "A1:A10", []excelize.ConditionalFormatOptions{ {Type: "duplicate", Criteria: "=", Format: format}, }, )
type: unique — The unique type is used to highlight unique cells in a range:
// Highlight cells rules: Not Equal To... err := f.SetConditionalFormat("Sheet1", "A1:A10", []excelize.ConditionalFormatOptions{ {Type: "unique", Criteria: "=", Format: format}, }, )
type: top — The top type is used to specify the top n values by number or
percentage in a range:
// Top/Bottom rules: Top 10. err := f.SetConditionalFormat("Sheet1", "H1:H10", []excelize.ConditionalFormatOptions{ { Type: "top", Criteria: "=", Format: format, Value: "6", }, }, )
The criteria can be used to indicate that a percentage condition is required:
err := f.SetConditionalFormat("Sheet1", "A1:A10", []excelize.ConditionalFormatOptions{ { Type: "top", Criteria: "=", Format: format, Value: "6", Percent: true, }, }, )
type: 2_color_scale — The 2_color_scale type is used to specify Excel’s «2
Color Scale» style conditional format:
// Color scales: 2 color. err := f.SetConditionalFormat("Sheet1", "A1:A10", []excelize.ConditionalFormatOptions{ { Type: "2_color_scale", Criteria: "=", MinType: "min", MaxType: "max", MinColor: "#F8696B", MaxColor: "#63BE7B", }, }, )
This conditional type can be modified with MinType, MaxType, MinValue,
MaxValue, MinColor and MaxColor, see below.
type: 3_color_scale — The 3_color_scale type is used to specify Excel’s «3
Color Scale» style conditional format:
// Color scales: 3 color. err := f.SetConditionalFormat("Sheet1", "A1:A10", []excelize.ConditionalFormatOptions{ { Type: "3_color_scale", Criteria: "=", MinType: "min", MidType: "percentile", MaxType: "max", MinColor: "#F8696B", MidColor: "#FFEB84", MaxColor: "#63BE7B", }, }, )
This conditional type can be modified with MinType, MidType, MaxType,
MinValue, MidValue, MaxValue, MinColor, MidColor and MaxColor, see
below.
type: data_bar — The data_bar type is used to specify Excel’s «Data Bar»
style conditional format.
MinType — The MinType and MaxType properties are available when the
conditional formatting type is 2_color_scale, 3_color_scale or data_bar.
The MidType is available for 3_color_scale. The properties are used as
follows:
// Data Bars: Gradient Fill. err := f.SetConditionalFormat("Sheet1", "K1:K10", []excelize.ConditionalFormatOptions{ { Type: "data_bar", Criteria: "=", MinType: "min", MaxType: "max", BarColor: "#638EC6", }, }, )
The available min/mid/max types are:
min (for MinType only) num percent percentile formula max (for MaxType only)
MidType — Used for 3_color_scale. Same as MinType, see above.
MaxType — Same as MinType, see above.
MinValue — The MinValue and MaxValue properties are available when the
conditional formatting type is 2_color_scale, 3_color_scale or data_bar.
MidValue — The MidValue is available for 3_color_scale. Same as MinValue,
see above.
MaxValue — Same as MinValue, see above.
MinColor — The MinColor and MaxColor properties are available when the
conditional formatting type is 2_color_scale, 3_color_scale or data_bar.
MidColor — The MidColor is available for 3_color_scale. The properties
are used as follows:
// Color scales: 3 color. err := f.SetConditionalFormat("Sheet1", "B1:B10", []excelize.ConditionalFormatOptions{ { Type: "3_color_scale", Criteria: "=", MinType: "min", MidType: "percentile", MaxType: "max", MinColor: "#F8696B", MidColor: "#FFEB84", MaxColor: "#63BE7B", }, }, )
MaxColor — Same as MinColor, see above.
BarColor — Used for data_bar. Same as MinColor, see above.
BarBorderColor — Used for sets the color for the border line of a data bar,
this is only visible in Excel 2010 and later.
BarDirection — sets the direction for data bars. The available options are:
context - Data bar direction is set by spreadsheet application based on the context of the data displayed. leftToRight - Data bar direction is from right to left. rightToLeft - Data bar direction is from left to right.
BarOnly — Used for set displays a bar data but not the data in the cells.
BarSolid — Used for turns on a solid (non-gradient) fill for data bars, this
is only visible in Excel 2010 and later.
IconStyle — The available options are:
3Arrows 3ArrowsGray 3Flags 3Signs 3Symbols 3Symbols2 3TrafficLights1 3TrafficLights2 4Arrows 4ArrowsGray 4Rating 4RedToBlack 4TrafficLights 5Arrows 5ArrowsGray 5Quarters 5Rating
ReverseIcons — Used for set reversed icons sets.
IconsOnly — Used for set displayed without the cell value.
StopIfTrue — used to set the «stop if true» feature of a conditional
formatting rule when more than one rule is applied to a cell or a range of
cells. When this parameter is set then subsequent rules are not evaluated
if the current rule is true.
SetDefaultFont changes the default font in the workbook.
func (f *File) SetDefinedName(definedName *DefinedName) error
SetDefinedName provides a function to set the defined names of the workbook
or worksheet. If not specified scope, the default scope is workbook.
For example:
err := f.SetDefinedName(&excelize.DefinedName{ Name: "Amount", RefersTo: "Sheet1!$A$2:$D$5", Comment: "defined name comment", Scope: "Sheet2", })
func (f *File) SetDocProps(docProperties *DocProperties) error
SetDocProps provides a function to set document core properties. The
properties that can be set are:
Property | Description ----------------+----------------------------------------------------------- Title | The name given to the resource. | Subject | The topic of the content of the resource. | Creator | An entity primarily responsible for making the content of | the resource. | Keywords | A delimited set of keywords to support searching and | indexing. This is typically a list of terms that are not | available elsewhere in the properties. | Description | An explanation of the content of the resource. | LastModifiedBy | The user who performed the last modification. The | identification is environment-specific. | Language | The language of the intellectual content of the resource. | Identifier | An unambiguous reference to the resource within a given | context. | Revision | The topic of the content of the resource. | ContentStatus | The status of the content. For example: Values might | include "Draft", "Reviewed" and "Final" | Category | A categorization of the content of this package. | Version | The version number. This value is set by the user or by | the application. | Created | The created time of the content of the resource which | represent in ISO 8601 UTC format, for example | "2019-06-04T22:00:10Z". | Modified | The modified time of the content of the resource which | represent in ISO 8601 UTC format, for example | "2019-06-04T22:00:10Z". |
For example:
err := f.SetDocProps(&excelize.DocProperties{ Category: "category", ContentStatus: "Draft", Created: "2019-06-04T22:00:10Z", Creator: "Go Excelize", Description: "This file created by Go Excelize", Identifier: "xlsx", Keywords: "Spreadsheet", LastModifiedBy: "Go Author", Modified: "2019-06-04T22:00:10Z", Revision: "0", Subject: "Test Subject", Title: "Test Title", Language: "en-US", Version: "1.0.0", })
SetHeaderFooter provides a function to set headers and footers by given
worksheet name and the control characters.
Headers and footers are specified using the following settings fields:
Fields | Description ------------------+----------------------------------------------------------- AlignWithMargins | Align header footer margins with page margins DifferentFirst | Different first-page header and footer indicator DifferentOddEven | Different odd and even page headers and footers indicator ScaleWithDoc | Scale header and footer with document scaling OddFooter | Odd Page Footer OddHeader | Odd Header EvenFooter | Even Page Footer EvenHeader | Even Page Header FirstFooter | First Page Footer FirstHeader | First Page Header
The following formatting codes can be used in 6 string type fields:
OddHeader, OddFooter, EvenHeader, EvenFooter, FirstFooter, FirstHeader
Formatting Code | Description ------------------------+------------------------------------------------------------------------- && | The character "&" | &font-size | Size of the text font, where font-size is a decimal font size in points | &"font name,font type" | A text font-name string, font name, and a text font-type string, | font type | &"-,Regular" | Regular text format. Toggles bold and italic modes to off | &A | Current worksheet's tab name | &B or &"-,Bold" | Bold text format, from off to on, or vice versa. The default mode is off | &D | Current date | &C | Center section | &E | Double-underline text format | &F | Current workbook's file name | &G | Drawing object as background (Not support currently) | &H | Shadow text format | &I or &"-,Italic" | Italic text format | &K | Text font color | | An RGB Color is specified as RRGGBB | | A Theme Color is specified as TTSNNN where TT is the theme color Id, | S is either "+" or "-" of the tint/shade value, and NNN is the | tint/shade value | &L | Left section | &N | Total number of pages | &O | Outline text format | &P[[+|-]n] | Without the optional suffix, the current page number in decimal | &R | Right section | &S | Strike through text format | &T | Current time | &U | Single-underline text format. If double-underline mode is on, the next | occurrence in a section specifier toggles double-underline mode to off; | otherwise, it toggles single-underline mode, from off to on, or vice | versa. The default mode is off | &X | Superscript text format | &Y | Subscript text format | &Z | Current workbook's file path
For example:
err := f.SetHeaderFooter("Sheet1", &excelize.HeaderFooterOptions{ DifferentFirst: true, DifferentOddEven: true, OddHeader: "&R&P", OddFooter: "&C&F", EvenHeader: "&L&P", EvenFooter: "&L&D&R&T", FirstHeader: `&CCenter &"-,Bold"Bold&"-,Regular"HeaderU+000A&D`, })
This example shows:
— The first page has its own header and footer
— Odd and even-numbered pages have different headers and footers
— Current page number in the right section of odd-page headers
— Current workbook’s file name in the center section of odd-page footers
— Current page number in the left section of even-page headers
— Current date in the left section and the current time in the right section
of even-page footers
— The text «Center Bold Header» on the first line of the center section of
the first page, and the date on the second line of the center section of
that same page
— No footer on the first page
SetPageLayout provides a function to sets worksheet page layout.
The following shows the paper size sorted by excelize index number:
Index | Paper Size -------+----------------------------------------------- 1 | Letter paper (8.5 in. by 11 in.) 2 | Letter small paper (8.5 in. by 11 in.) 3 | Tabloid paper (11 in. by 17 in.) 4 | Ledger paper (17 in. by 11 in.) 5 | Legal paper (8.5 in. by 14 in.) 6 | Statement paper (5.5 in. by 8.5 in.) 7 | Executive paper (7.25 in. by 10.5 in.) 8 | A3 paper (297 mm by 420 mm) 9 | A4 paper (210 mm by 297 mm) 10 | A4 small paper (210 mm by 297 mm) 11 | A5 paper (148 mm by 210 mm) 12 | B4 paper (250 mm by 353 mm) 13 | B5 paper (176 mm by 250 mm) 14 | Folio paper (8.5 in. by 13 in.) 15 | Quarto paper (215 mm by 275 mm) 16 | Standard paper (10 in. by 14 in.) 17 | Standard paper (11 in. by 17 in.) 18 | Note paper (8.5 in. by 11 in.) 19 | #9 envelope (3.875 in. by 8.875 in.) 20 | #10 envelope (4.125 in. by 9.5 in.) 21 | #11 envelope (4.5 in. by 10.375 in.) 22 | #12 envelope (4.75 in. by 11 in.) 23 | #14 envelope (5 in. by 11.5 in.) 24 | C paper (17 in. by 22 in.) 25 | D paper (22 in. by 34 in.) 26 | E paper (34 in. by 44 in.) 27 | DL envelope (110 mm by 220 mm) 28 | C5 envelope (162 mm by 229 mm) 29 | C3 envelope (324 mm by 458 mm) 30 | C4 envelope (229 mm by 324 mm) 31 | C6 envelope (114 mm by 162 mm) 32 | C65 envelope (114 mm by 229 mm) 33 | B4 envelope (250 mm by 353 mm) 34 | B5 envelope (176 mm by 250 mm) 35 | B6 envelope (176 mm by 125 mm) 36 | Italy envelope (110 mm by 230 mm) 37 | Monarch envelope (3.875 in. by 7.5 in.). 38 | 6 3/4 envelope (3.625 in. by 6.5 in.) 39 | US standard fanfold (14.875 in. by 11 in.) 40 | German standard fanfold (8.5 in. by 12 in.) 41 | German legal fanfold (8.5 in. by 13 in.) 42 | ISO B4 (250 mm by 353 mm) 43 | Japanese postcard (100 mm by 148 mm) 44 | Standard paper (9 in. by 11 in.) 45 | Standard paper (10 in. by 11 in.) 46 | Standard paper (15 in. by 11 in.) 47 | Invite envelope (220 mm by 220 mm) 50 | Letter extra paper (9.275 in. by 12 in.) 51 | Legal extra paper (9.275 in. by 15 in.) 52 | Tabloid extra paper (11.69 in. by 18 in.) 53 | A4 extra paper (236 mm by 322 mm) 54 | Letter transverse paper (8.275 in. by 11 in.) 55 | A4 transverse paper (210 mm by 297 mm) 56 | Letter extra transverse paper (9.275 in. by 12 in.) 57 | SuperA/SuperA/A4 paper (227 mm by 356 mm) 58 | SuperB/SuperB/A3 paper (305 mm by 487 mm) 59 | Letter plus paper (8.5 in. by 12.69 in.) 60 | A4 plus paper (210 mm by 330 mm) 61 | A5 transverse paper (148 mm by 210 mm) 62 | JIS B5 transverse paper (182 mm by 257 mm) 63 | A3 extra paper (322 mm by 445 mm) 64 | A5 extra paper (174 mm by 235 mm) 65 | ISO B5 extra paper (201 mm by 276 mm) 66 | A2 paper (420 mm by 594 mm) 67 | A3 transverse paper (297 mm by 420 mm) 68 | A3 extra transverse paper (322 mm by 445 mm) 69 | Japanese Double Postcard (200 mm x 148 mm) 70 | A6 (105 mm x 148 mm) 71 | Japanese Envelope Kaku #2 72 | Japanese Envelope Kaku #3 73 | Japanese Envelope Chou #3 74 | Japanese Envelope Chou #4 75 | Letter Rotated (11in x 8 1/2 11 in) 76 | A3 Rotated (420 mm x 297 mm) 77 | A4 Rotated (297 mm x 210 mm) 78 | A5 Rotated (210 mm x 148 mm) 79 | B4 (JIS) Rotated (364 mm x 257 mm) 80 | B5 (JIS) Rotated (257 mm x 182 mm) 81 | Japanese Postcard Rotated (148 mm x 100 mm) 82 | Double Japanese Postcard Rotated (148 mm x 200 mm) 83 | A6 Rotated (148 mm x 105 mm) 84 | Japanese Envelope Kaku #2 Rotated 85 | Japanese Envelope Kaku #3 Rotated 86 | Japanese Envelope Chou #3 Rotated 87 | Japanese Envelope Chou #4 Rotated 88 | B6 (JIS) (128 mm x 182 mm) 89 | B6 (JIS) Rotated (182 mm x 128 mm) 90 | (12 in x 11 in) 91 | Japanese Envelope You #4 92 | Japanese Envelope You #4 Rotated 93 | PRC 16K (146 mm x 215 mm) 94 | PRC 32K (97 mm x 151 mm) 95 | PRC 32K(Big) (97 mm x 151 mm) 96 | PRC Envelope #1 (102 mm x 165 mm) 97 | PRC Envelope #2 (102 mm x 176 mm) 98 | PRC Envelope #3 (125 mm x 176 mm) 99 | PRC Envelope #4 (110 mm x 208 mm) 100 | PRC Envelope #5 (110 mm x 220 mm) 101 | PRC Envelope #6 (120 mm x 230 mm) 102 | PRC Envelope #7 (160 mm x 230 mm) 103 | PRC Envelope #8 (120 mm x 309 mm) 104 | PRC Envelope #9 (229 mm x 324 mm) 105 | PRC Envelope #10 (324 mm x 458 mm) 106 | PRC 16K Rotated 107 | PRC 32K Rotated 108 | PRC 32K(Big) Rotated 109 | PRC Envelope #1 Rotated (165 mm x 102 mm) 110 | PRC Envelope #2 Rotated (176 mm x 102 mm) 111 | PRC Envelope #3 Rotated (176 mm x 125 mm) 112 | PRC Envelope #4 Rotated (208 mm x 110 mm) 113 | PRC Envelope #5 Rotated (220 mm x 110 mm) 114 | PRC Envelope #6 Rotated (230 mm x 120 mm) 115 | PRC Envelope #7 Rotated (230 mm x 160 mm) 116 | PRC Envelope #8 Rotated (309 mm x 120 mm) 117 | PRC Envelope #9 Rotated (324 mm x 229 mm) 118 | PRC Envelope #10 Rotated (458 mm x 324 mm)
SetPageMargins provides a function to set worksheet page margins.
SetPanes provides a function to create and remove freeze panes and split panes
by given worksheet name and panes options.
ActivePane defines the pane that is active. The possible values for this
attribute are defined in the following table:
Enumeration Value | Description ---------------------------------+------------------------------------------------------------- bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal | splits are applied. | | This value is also used when only a horizontal split has | been applied, dividing the pane into upper and lower | regions. In that case, this value specifies the bottom | pane. | bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal | splits are applied. | topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits | are applied. | | This value is also used when only a horizontal split has | been applied, dividing the pane into upper and lower | regions. In that case, this value specifies the top pane. | | This value is also used when only a vertical split has | been applied, dividing the pane into right and left | regions. In that case, this value specifies the left pane | topRight (Top Right Pane) | Top right pane, when both vertical and horizontal | splits are applied. | | This value is also used when only a vertical split has | been applied, dividing the pane into right and left | regions. In that case, this value specifies the right | pane.
Pane state type is restricted to the values supported currently listed in the following table:
Enumeration Value | Description ---------------------------------+------------------------------------------------------------- frozen (Frozen) | Panes are frozen, but were not split being frozen. In | this state, when the panes are unfrozen again, a single | pane results, with no split. | | In this state, the split bars are not adjustable. | split (Split) | Panes are split, but not frozen. In this state, the split | bars are adjustable by the user.
XSplit (Horizontal Split Position): Horizontal position of the split, in
1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
indicates the number of columns visible in the top pane.
YSplit (Vertical Split Position): Vertical position of the split, in 1/20th
of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
number of rows visible in the left pane. The possible values for this
attribute are defined by the W3C XML Schema double datatype.
TopLeftCell: Location of the top left visible cell in the bottom right pane
(when in Left-To-Right mode).
SQRef (Sequence of References): Range of the selection. Can be non-contiguous
set of ranges.
An example of how to freeze column A in the Sheet1 and set the active cell on
Sheet1!K16:
err := f.SetPanes("Sheet1", &excelize.Panes{ Freeze: true, Split: false, XSplit: 1, YSplit: 0, TopLeftCell: "B1", ActivePane: "topRight", Panes: []excelize.PaneOptions{ {SQRef: "K16", ActiveCell: "K16", Pane: "topRight"}, }, })
An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
ranges on Sheet1!A11:XFD11:
err := f.SetPanes("Sheet1", &excelize.Panes{ Freeze: true, Split: false, XSplit: 0, YSplit: 9, TopLeftCell: "A34", ActivePane: "bottomLeft", Panes: []excelize.PaneOptions{ {SQRef: "A11:XFD11", ActiveCell: "A11", Pane: "bottomLeft"}, }, })
An example of how to create split panes in the Sheet1 and set the active cell
on Sheet1!J60:
err := f.SetPanes("Sheet1", &excelize.Panes{ Freeze: false, Split: true, XSplit: 3270, YSplit: 1800, TopLeftCell: "N57", ActivePane: "bottomLeft", Panes: []excelize.PaneOptions{ {SQRef: "I36", ActiveCell: "I36"}, {SQRef: "G33", ActiveCell: "G33", Pane: "topRight"}, {SQRef: "J60", ActiveCell: "J60", Pane: "bottomLeft"}, {SQRef: "O60", ActiveCell: "O60", Pane: "bottomRight"}, }, })
An example of how to unfreeze and remove all panes on Sheet1:
err := f.SetPanes("Sheet1", &excelize.Panes{Freeze: false, Split: false})
SetRowHeight provides a function to set the height of a single row. For
example, set the height of the first row in Sheet1:
err := f.SetRowHeight("Sheet1", 1, 50)
SetRowOutlineLevel provides a function to set outline level number of a
single row by given worksheet name and Excel row number. The value of
parameter ‘level’ is 1-7. For example, outline row 2 in Sheet1 to level 1:
err := f.SetRowOutlineLevel("Sheet1", 2, 1)
SetRowStyle provides a function to set the style of rows by given worksheet
name, row range, and style ID. Note that this will overwrite the existing
styles for the rows, it won’t append or merge style with existing styles.
For example set style of row 1 on Sheet1:
err := f.SetRowStyle("Sheet1", 1, 1, styleID)
Set style of rows 1 to 10 on Sheet1:
err := f.SetRowStyle("Sheet1", 1, 10, styleID)
SetRowVisible provides a function to set visible of a single row by given
worksheet name and Excel row number. For example, hide row 2 in Sheet1:
err := f.SetRowVisible("Sheet1", 2, false)
func (f *File) SetSheetBackground(sheet, picture string) error
SetSheetBackground provides a function to set background picture by given
worksheet name and file path. Supported image types: BMP, EMF, EMZ, GIF,
JPEG, JPG, PNG, SVG, TIF, TIFF, WMF, and WMZ.
func (f *File) SetSheetBackgroundFromBytes(sheet, extension string, picture []byte) error
SetSheetBackgroundFromBytes provides a function to set background picture by
given worksheet name, extension name and image data. Supported image types:
BMP, EMF, EMZ, GIF, JPEG, JPG, PNG, SVG, TIF, TIFF, WMF, and WMZ.
func (f *File) SetSheetCol(sheet, cell string, slice interface{}) error
SetSheetCol writes an array to column by given worksheet name, starting
cell reference and a pointer to array type ‘slice’. For example, writes an
array to column B start with the cell B6 on Sheet1:
err := f.SetSheetCol("Sheet1", "B6", &[]interface{}{"1", nil, 2})
SetSheetDimension provides the method to set or remove the used range of the
worksheet by a given range reference. It specifies the row and column bounds
of used cells in the worksheet. The range reference is set using the A1
reference style(e.g., «A1:D5»). Passing an empty range reference will remove
the used range of the worksheet.
SetSheetName provides a function to set the worksheet name by given source and
target worksheet names. Maximum 31 characters are allowed in sheet title and
this function only changes the name of the sheet and will not update the
sheet name in the formula or reference associated with the cell. So there
may be problem formula error or reference missing.
SetSheetProps provides a function to set worksheet properties.
func (f *File) SetSheetRow(sheet, cell string, slice interface{}) error
SetSheetRow writes an array to row by given worksheet name, starting
cell reference and a pointer to array type ‘slice’. This function is
concurrency safe. For example, writes an array to row 6 start with the cell
B6 on Sheet1:
err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
SetSheetView sets sheet view options. The viewIndex may be negative and if
so is counted backward (-1 is the last view).
SetSheetVisible provides a function to set worksheet visible by given
worksheet name. A workbook must contain at least one visible worksheet. If
the given worksheet has been activated, this setting will be invalidated.
The third optional veryHidden parameter only works when visible was false.
For example, hide Sheet1:
err := f.SetSheetVisible("Sheet1", false)
func (f *File) SetWorkbookProps(opts *WorkbookPropsOptions) error
SetWorkbookProps provides a function to sets workbook properties.
func (f *File) UngroupSheets() error
UngroupSheets provides a function to ungroup worksheets.
UnmergeCell provides a function to unmerge a given range reference.
For example unmerge range reference D3:E9 on Sheet1:
err := f.UnmergeCell("Sheet1", "D3", "E9")
Attention: overlapped range will also be unmerged.
UnprotectSheet provides a function to remove protection for a sheet,
specified the second optional password parameter to remove sheet
protection with password verification.
UnprotectWorkbook provides a function to remove protection for workbook,
specified the optional password parameter to remove workbook protection with
password verification.
func (f *File) UnsetConditionalFormat(sheet, rangeRef string) error
UnsetConditionalFormat provides a function to unset the conditional format
by given worksheet name and range reference.
func (f *File) UpdateLinkedValue() error
UpdateLinkedValue fix linked values within a spreadsheet are not updating in
Office Excel application. This function will be remove value tag when met a
cell have a linked value. Reference
https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating
Notice: after opening generated workbook, Excel will update the linked value
and generate a new value and will prompt to save the file or not.
For example:
<row r="19" spans="2:2"> <c r="B19"> <f>SUM(Sheet2!D2,Sheet2!D11)</f> <v>100</v> </c> </row>
to
<row r="19" spans="2:2"> <c r="B19"> <f>SUM(Sheet2!D2,Sheet2!D11)</f> </c> </row>
Write provides a function to write to an io.Writer.
WriteTo implements io.WriterTo to write the file.
WriteToBuffer provides a function to get bytes.Buffer from the saved file,
and it allocates space in memory. Be careful when the file size is large.
Fill directly maps the fill settings of the cells.
Font directly maps the font settings of the fonts.
FormulaOpts can be passed to SetCellFormula to use other formula types.
GraphicOptions directly maps the format settings of the picture.
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.
RGBA returns the alpha-premultiplied red, green, blue and alpha values
for the HSL.
type HeaderFooterOptions struct { }
HeaderFooterOptions directly maps the settings of header and footer.
type HyperlinkOpts struct { Display *string Tooltip *string }
HyperlinkOpts can be passed to SetCellHyperlink to set optional hyperlink
attributes (e.g. display value)
type KeyData struct { SaltSize int `xml:"saltSize,attr"` BlockSize int `xml:"blockSize,attr"` KeyBits int `xml:"keyBits,attr"` HashSize int `xml:"hashSize,attr"` CipherAlgorithm string `xml:"cipherAlgorithm,attr"` CipherChaining string `xml:"cipherChaining,attr"` HashAlgorithm string `xml:"hashAlgorithm,attr"` SaltValue string `xml:"saltValue,attr"` }
KeyData specifies the cryptographic attributes used to encrypt the data.
type KeyEncryptor struct { XMLName xml.Name `xml:"keyEncryptor"` URI string `xml:"uri,attr"` EncryptedKey EncryptedKey `xml:"encryptedKey"` }
KeyEncryptor specifies that the schema used by this encryptor is the schema
specified for password-based encryptors.
type KeyEncryptors struct {
KeyEncryptor []KeyEncryptor `xml:"keyEncryptor"`
}
KeyEncryptors specifies the key encryptors used to encrypt the data.
MergeCell define a merged cell data.
It consists of the following structure.
example: []string{«D4:E10», «cell value»}
GetCellValue returns merged cell value.
GetEndAxis returns the bottom right cell reference of merged range, for
example: «D4».
GetStartAxis returns the top left cell reference of merged range, for
example: «C2».
type Options struct { MaxCalcIterations uint Password string RawCellValue bool UnzipSizeLimit int64 UnzipXMLSizeLimit int64 }
Options define the options for open and reading spreadsheet.
MaxCalcIterations specifies the maximum iterations for iterative
calculation, the default value is 0.
Password specifies the password of the spreadsheet in plain text.
RawCellValue specifies if apply the number format for the cell value or get
the raw value.
UnzipSizeLimit specifies the unzip size limit in bytes on open the
spreadsheet, this value should be greater than or equal to
UnzipXMLSizeLimit, the default size limit is 16GB.
UnzipXMLSizeLimit specifies the memory limit on unzipping worksheet and
shared string table in bytes, worksheet XML will be extracted to system
temporary directory when the file size is over this value, this value
should be less than or equal to UnzipSizeLimit, the default value is
16MB.
PageLayoutMarginsOptions directly maps the settings of page layout margins.
type PageLayoutOptions struct { Size *int Orientation *string FirstPageNumber *uint AdjustTo *uint FitToHeight *int FitToWidth *int BlackAndWhite *bool }
PageLayoutOptions directly maps the settings of page layout.
PaneOptions directly maps the settings of the pane.
Panes directly maps the settings of the panes.
type Picture struct { Extension string File []byte Format *GraphicOptions }
Picture maps the format settings of the picture.
PivotTableField directly maps the field settings of the pivot table.
Subtotal specifies the aggregation function that applies to this data
field. The default value is sum. The possible values for this attribute
are:
Average Count CountNums Max Min Product StdDev StdDevp Sum Var Varp
Name specifies the name of the data field. Maximum 255 characters
are allowed in data field name, excess characters will be truncated.
type PivotTableOptions struct { DataRange string PivotTableRange string Rows []PivotTableField Columns []PivotTableField Data []PivotTableField Filter []PivotTableField RowGrandTotals bool ColGrandTotals bool ShowDrill bool UseAutoFormatting bool PageOverThenDown bool MergeItem bool CompactData bool ShowError bool ShowRowStripes bool ShowColStripes bool ShowLastColumn bool PivotTableStyleName string }
PivotTableOptions directly maps the format settings of the pivot table.
PivotTableStyleName: The built-in pivot table style names
PivotStyleLight1 - PivotStyleLight28 PivotStyleMedium1 - PivotStyleMedium28 PivotStyleDark1 - PivotStyleDark28
type Protection struct { Hidden bool Locked bool }
Protection directly maps the protection settings of the cells.
type RichTextRun struct { Font *Font Text string }
RichTextRun directly maps the settings of the rich text run.
RowOpts define the options for the set row, it can be used directly in
StreamWriter.SetRow to specify the style and properties of the row.
Rows defines an iterator to a sheet.
func (rows *Rows) Close() error
Close closes the open worksheet XML file in the system temporary
directory.
func (*Rows) Columns ¶
Columns return the current row’s column values. This fetches the worksheet
data as a stream, returns each cell in a row as is, and will not skip empty
rows in the tail of the worksheet.
func (rows *Rows) Error() error
Error will return the error when the error occurs.
func (rows *Rows) GetRowOpts() RowOpts
GetRowOpts will return the RowOpts of the current row.
func (rows *Rows) Next() bool
Next will return true if find the next row element.
Shape directly maps the format settings of the shape.
ShapeColor directly maps the color settings of the shape.
ShapeLine directly maps the line settings of the shape.
SheetPropsOptions directly maps the settings of sheet view.
SheetProtectionOptions directly maps the settings of worksheet protection.
SparklineOptions directly maps the settings of the sparkline.
Stack defined an abstract data type that serves as a collection of elements.
NewStack create a new stack.
func (stack *Stack) Empty() bool
Empty the stack.
func (stack *Stack) Len() int
Len return the number of items in the stack.
func (stack *Stack) Peek() interface{}
Peek view the top item on the stack.
func (stack *Stack) Pop() interface{}
Pop the top item of the stack and return it.
func (stack *Stack) Push(value interface{})
Push a value onto the top of the stack.
type StandardEncryptionHeader ¶
StandardEncryptionHeader structure is used by ECMA-376 document encryption
[ECMA-376] and Office binary document RC4 CryptoAPI encryption, to specify
encryption properties for an encrypted stream.
type StandardEncryptionVerifier ¶
type StandardEncryptionVerifier struct { SaltSize uint32 Salt []byte EncryptedVerifier []byte VerifierHashSize uint32 EncryptedVerifierHash []byte }
StandardEncryptionVerifier structure is used by Office Binary Document RC4
CryptoAPI Encryption and ECMA-376 Document Encryption. Every usage of this
structure MUST specify the hashing algorithm and encryption algorithm used
in the EncryptionVerifier structure.
type StreamWriter struct { Sheet string SheetID int }
StreamWriter defined the type of stream writer.
func (sw *StreamWriter) AddTable(table *Table) error
AddTable creates an Excel table for the StreamWriter using the given
cell range and format set. For example, create a table of A1:D5:
err := sw.AddTable(&excelize.Table{Range: "A1:D5"})
Create a table of F2:H6 with format set:
disable := false err := sw.AddTable(&excelize.Table{ Range: "F2:H6", Name: "table", StyleName: "TableStyleMedium2", ShowFirstColumn: true, ShowLastColumn: true, ShowRowStripes: &disable, ShowColumnStripes: true, })
Note that the table must be at least two lines including the header. The
header cells must contain strings and must be unique.
Currently, only one table is allowed for a StreamWriter. AddTable must be
called after the rows are written but before Flush.
See File.AddTable for details on the table format.
Flush ending the streaming writing process.
InsertPageBreak creates a page break to determine where the printed page ends
and where begins the next one by a given cell reference, the content before
the page break will be printed on one page and after the page break on
another.
MergeCell provides a function to merge cells by a given range reference for
the StreamWriter. Don’t create a merged cell that overlaps with another
existing merged cell.
SetColWidth provides a function to set the width of a single column or
multiple columns for the StreamWriter. Note that you must call
the ‘SetColWidth’ function before the ‘SetRow’ function. For example set
the width column B:C as 20:
err := sw.SetColWidth(2, 3, 20)
func (sw *StreamWriter) SetPanes(panes *Panes) error
SetPanes provides a function to create and remove freeze panes and split
panes by giving panes options for the StreamWriter. Note that you must call
the ‘SetPanes’ function before the ‘SetRow’ function.
func (sw *StreamWriter) SetRow(cell string, values []interface{}, opts ...RowOpts) error
SetRow writes an array to stream rows by giving starting cell reference and a
pointer to an array of values. Note that you must call the ‘Flush’ function
to end the streaming writing process.
As a special case, if Cell is used as a value, then the Cell.StyleID will be
applied to that cell.
type Style struct { Border []Border Fill Fill Font *Font Alignment *Alignment Protection *Protection NumFmt int DecimalPlaces int CustomNumFmt *string Lang string NegRed bool }
Style directly maps the style settings of the cells.
Table directly maps the format settings of the table.
ViewOptions directly maps the settings of sheet view.
type WorkbookPropsOptions struct { Date1904 *bool FilterPrivacy *bool CodeName *string }
WorkbookPropsOptions directly maps the settings of workbook proprieties.
type WorkbookProtectionOptions struct { AlgorithmName string Password string LockStructure bool LockWindows bool }
WorkbookProtectionOptions directly maps the settings of workbook protection.
Apr 12, 2019
3 min read
Excelize
Excelize is a library written in pure Go providing a set of functions that allow you to write to and read from XLSX files. Supports reading and writing XLSX file generated by Microsoft Excel™ 2007 and later. Supports saving a file without losing original charts of XLSX. This library needs Go version 1.8 or later. The full API docs can be seen using go’s built-in documentation tool, or online at godoc.org and docs reference.
Basic Usage
Installation
go get github.com/360EntSecGroup-Skylar/excelize
Create XLSX file
Here is a minimal example usage that will create XLSX file.
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx := excelize.NewFile()
// Create a new sheet.
index := xlsx.NewSheet("Sheet2")
// Set value of a cell.
xlsx.SetCellValue("Sheet2", "A2", "Hello world.")
xlsx.SetCellValue("Sheet1", "B2", 100)
// Set active sheet of the workbook.
xlsx.SetActiveSheet(index)
// Save xlsx file by the given path.
err := xlsx.SaveAs("./Book1.xlsx")
if err != nil {
fmt.Println(err)
}
}
Reading XLSX file
The following constitutes the bare to read a XLSX document.
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx, err := excelize.OpenFile("./Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Get value from cell by given worksheet name and axis.
cell := xlsx.GetCellValue("Sheet1", "B2")
fmt.Println(cell)
// Get all the rows in the Sheet1.
rows := xlsx.GetRows("Sheet1")
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "t")
}
fmt.Println()
}
}
Add chart to XLSX file
With Excelize chart generation and management is as easy as a few lines of code. You can build charts based off data in your worksheet or generate charts without any data in your worksheet at all.
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
xlsx := excelize.NewFile()
for k, v := range categories {
xlsx.SetCellValue("Sheet1", k, v)
}
for k, v := range values {
xlsx.SetCellValue("Sheet1", k, v)
}
xlsx.AddChart("Sheet1", "E1", `{"type":"col3DClustered","series":[{"name":"Sheet1!$A$2","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$2:$D$2"},{"name":"Sheet1!$A$3","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$3:$D$3"},{"name":"Sheet1!$A$4","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$4:$D$4"}],"title":{"name":"Fruit 3D Clustered Column Chart"}}`)
// Save xlsx file by the given path.
err := xlsx.SaveAs("./Book1.xlsx")
if err != nil {
fmt.Println(err)
}
}
Add picture to XLSX file
package main
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx, err := excelize.OpenFile("./Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Insert a picture.
err = xlsx.AddPicture("Sheet1", "A2", "./image1.png", "")
if err != nil {
fmt.Println(err)
}
// Insert a picture to worksheet with scaling.
err = xlsx.AddPicture("Sheet1", "D2", "./image2.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`)
if err != nil {
fmt.Println(err)
}
// Insert a picture offset in the cell with printing support.
err = xlsx.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`)
if err != nil {
fmt.Println(err)
}
// Save the xlsx file with the origin path.
err = xlsx.Save()
if err != nil {
fmt.Println(err)
}
}
GitHub
John was the first writer to have joined golangexample.com. He has since then inculcated very effective writing and reviewing culture at golangexample which rivals have found impossible to imitate.
Previous Post
Golang HTML to PDF Converter
Next Post
A WebAssembly framework to build GUI with Go
Table of Contents
This tutorial shows how to use excelize package to read and write excel files, read a single cell and a row of cells, update a single cell and a row of cells.
Golang read Excel files
To read Excel sheets in Go, you can use a third-party library called “excelize”. It provides a simple and efficient way to read and write Excel files.
Firstly you need to install the excelize package using the following command:
go get github.com/xuri/excelize/v2
Here’s an example code that shows how to read an Excel sheet using excelize:
Sample excel file:
sample.xlsx ← Click this link to download the sample excel file
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
f, err := excelize.OpenFile("sample.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Get value from cell by given sheet name and axis.
cellValue, err := f.GetCellValue("Sheet1", "B2")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(cellValue)
// Get all the rows in the sheet.
rows, err := f.GetRows("Sheet1")
if err != nil {
fmt.Println(err)
return
}
// Iterate over the rows and print the cell values.
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "t")
}
fmt.Println()
}
}
If you save the above code into main.go file, you can run it using the following command.
You will see the following results.
Update cell values
Update a single cell
To update cell values in an Excel sheet using Go and the excelize package, you can use the SetCellValue method of the File struct. Here’s an example code that shows how to update a cell value:
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
f, err := excelize.OpenFile("sample.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Set value of cell D4 to 88
err = f.SetCellValue("Sheet1", "D4", 88)
if err != nil {
fmt.Println(err)
return
}
// Save the changes to the file.
err = f.Save()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Cell D4 updated successfully.")
}
If you save the above code into main.go file, you can run it using the following command.
You will see the following results.
The D4 value will be changed like below.
In this example, we first open the Excel file using the OpenFile method of the excelize package. We then use the SetCellValue method to set the value of cell D4 to 88. Finally, we save the changes to the file using the Save method.
Update multiple cells
You can also update the value of multiple cells at once using the SetSheetRow method. Here’s an example:
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
f, err := excelize.OpenFile("sample.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Set values of cells B3, C3, D3 to "Jack", "Physics", 90
data := []interface{}{"Jack", "Physics", 90}
err = f.SetSheetRow("Sheet1", "B3", &data)
if err != nil {
fmt.Println(err)
return
}
// Save the changes to the file.
err = f.Save()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Cells B3, C3, D3 updated successfully.")
}
If you save the above code into main.go file, you can run it using the following command.
You will see the following results.
The D4 value will be changed like below.
Формулы, сводные таблицы и плагины предоставляют способы преобразования или управления вашими данными, если они находятся в формате CSV или XLSX. Но что, если вы заинтересованы в постоянной загрузке данных в общий отчет, который другим членам команды будет проще использовать в Excel или Google Таблицах?
Excelize – это библиотека Go для создания таблиц, совместимых с Excel, с поддержкой встраивания формул, стилей, диаграмм и т. Д. Недавно я работал над проектом автоматизации, в котором я использовал Go и Excelize для каталогизации структуры каталогов и превращения этой информации в автоматически обновляемую электронную таблицу.
Использование Go для такого легкого типа «ETL-подобной» рабочей нагрузки было захватывающим опытом, и я хотел поделиться некоторыми идеями, которые я получил во время работы с Excelize.
Определение стиля
Неудивительно, что в Excel есть система стилей, встроенная в электронную таблицу, когда вы меняете атрибуты фона, текста или границы ячейки. Мне потребовалось немного больше времени, чем я хотел бы признать, чтобы понять, как Excelize обрабатывает стили. В частности, многие примеры документации предоставляют объект стиля в виде строки JSON.
Это не то, как вы хотели бы структурировать свои стили, поскольку вы теряете все проверки типов и должны обрабатывать escape-символы и форматирование JSON вручную. Оказывается, NewStyle
функция поддерживает interface{}
параметр, и когда вы отодвигаете крышки, эта функция просто демаршалирует вашу строку в Style
объект.
Если мы сделаем еще один шаг вперед в приведенном выше примере, вы можете определить Style
структуру inline. Теперь вам не нужно беспокоиться о написании JSON вручную или о том, чтобы испортить типы отдельных атрибутов.
Последнее замечание о стилях: некоторые атрибуты, такие как граница, вводятся так, чтобы принимать фрагмент строк. Если вы похожи на меня, это создает впечатление, что у вас может быть любое количество определений стиля границы, что не имеет смысла.
Оказывается, как и в CSS, ожидается определение четырех структур Border для четырех сторон ячейки (сверху, слева, справа, снизу). В примере слева вы заметите, что вы назначаете каждую сторону, устанавливая Type
атрибут.
Использование среза карты для этой структуры данных кажется интересным, но может иметь некоторые скрытые преимущества. Если у вас есть какие-либо мысли по этому поводу, я хотел бы услышать об этом в комментариях.
Индексирование стилей
Excelize создает индекс стилей, которые встраиваются в электронную таблицу; к сожалению, он предоставляет этот индекс только через инкрементный идентификатор. Я предполагаю, что именно так Excel обрабатывает эту информацию внутри, но я обнаружил, что это немного подвержено ошибкам, поскольку я добавил больше стилей. Я решил создать централизованный указатель этих стилей, зарегистрировав их заранее, а затем использовал, map[string]int
чтобы прикрепить имя к внутреннему идентификатору стиля.
Это позволяет мне вводить индекс стиля в различные функции и получать стиль по его имени. Я также написал методы оболочки для StyleIndex
структуры, чтобы обеспечить лучшее автозаполнение и абстрагироваться от базового ключа, если мне нужно будет изменить его в будущем.
Конфигурация ячейки
Excelize предоставляет функции для индивидуальной настройки атрибута ячейки, но не имеет функций более высокого уровня, которые группируют вместе стандартные конфигурации. Вероятно, это был правильный призыв для библиотеки в целом, но он приводил к появлению большого количества повторяющегося кода для выполнения одного и того же набора действий каждый раз. Я написал несколько вспомогательных функций, таких как пример ниже, в котором я сгруппировал объединение нескольких ячеек и установил стили и значения.
Вы также должны заметить StyleIndex
структуру, которая вводится в функцию. Я ходил туда-сюда по поводу того, следует ли передавать индекс или передавать идентификатор стиля с одного уровня выше. Я не уверен, какой вариант я предпочитаю больше, поскольку у каждого есть свои компромиссы в отношении возможности повторного использования.
- Если каждый вызов функции указывает свой собственный идентификатор стиля, это делает ее более универсальной и многоразовой.
- Определение отдельной функции для каждого стиля означает, что конечному пользователю не нужно иметь столько знаний об используемых стилях.
Есть ли у вас какие-нибудь мысли по поводу этого компромисса? Возможно, вы столкнулись с этой проблемой в другой системе стилей.
Создание смещений ячеек и строк при итерации данных
В какой-то момент вам нужно будет программным способом определить, в какую строку и столбец вам нужно записать фрагмент данных. Ниже приведен пример того, как я добился этого, используя ColumnNumberToName
функцию и значение смещения. Это позволило мне рассчитать позицию столбца для нескольких фрагментов данных без каких-либо вычислений ASCII для вычисления того, что следует за столбцом AX1
.
Заключение
Мне понравилось использовать Excelize для автоматизации создания электронных таблиц со встроенным богатым содержанием. Это очень похоже на API нижнего уровня поверх формата файла Excel, а это означает, что вам придется потратить некоторое время на создание функций более высокого уровня для себя. Вы использовали Excelize раньше или, возможно, другую библиотеку Excel на другом языке?
Просмотры: 1 481
xuri
Posted on Jan 3, 2019
• Updated on May 25, 2022
Excelize is a library written in pure Go providing a set of functions that allow you to write to and read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and writing spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports complex components by high compatibility, and provided streaming API for generating or reading data from a worksheet with huge amounts of data.
GitHub: github.com/xuri/excelize
Basic Usage
Installation
go get github.com/xuri/excelize/v2
Enter fullscreen mode
Exit fullscreen mode
Create XLSX file
Here is a minimal example usage that will create XLSX file.
package main
import "github.com/xuri/excelize/v2"
func main() {
f := excelize.NewFile()
// Create a new sheet.
index := f.NewSheet("Sheet2")
// Set value of a cell.
f.SetCellValue("Sheet2", "A2", "Hello world.")
f.SetCellValue("Sheet1", "B2", 100)
// Set active sheet of the workbook.
f.SetActiveSheet(index)
// Save xlsx file by the given path.
if err := f.SaveAs("Book1.xlsx"); err != nil {
println(err.Error())
}
}
Enter fullscreen mode
Exit fullscreen mode
Reading XLSX file
The following constitutes the bare to read a XLSX document.
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
defer func() {
// Close the spreadsheet.
if err := f.Close(); err != nil {
fmt.Println(err)
}
}()
// Get value from cell by given worksheet name and axis.
cell, err := f.GetCellValue("Sheet1", "B2")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(cell)
// Get all the rows in the Sheet1.
rows, err := f.GetRows("Sheet1")
if err != nil {
fmt.Println(err)
return
}
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "t")
}
fmt.Println()
}
}
Enter fullscreen mode
Exit fullscreen mode
Add chart to XLSX file
With Excelize chart generation and management is as easy as a few lines of code. You can build charts based off data in your worksheet or generate charts without any data in your worksheet at all.
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
categories := map[string]string{
"A2": "Small", "A3": "Normal", "A4": "Large",
"B1": "Apple", "C1": "Orange", "D1": "Pear"}
values := map[string]int{
"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
f := excelize.NewFile()
for k, v := range categories {
f.SetCellValue("Sheet1", k, v)
}
for k, v := range values {
f.SetCellValue("Sheet1", k, v)
}
if err := f.AddChart("Sheet1", "E1", `{
"type": "col3DClustered",
"series": [
{
"name": "Sheet1!$A$2",
"categories": "Sheet1!$B$1:$D$1",
"values": "Sheet1!$B$2:$D$2"
},
{
"name": "Sheet1!$A$3",
"categories": "Sheet1!$B$1:$D$1",
"values": "Sheet1!$B$3:$D$3"
},
{
"name": "Sheet1!$A$4",
"categories": "Sheet1!$B$1:$D$1",
"values": "Sheet1!$B$4:$D$4"
}],
"title":
{
"name": "Fruit 3D Clustered Column Chart"
}
}`); err != nil {
fmt.Println(err)
return
}
// Save spreadsheet by the given path.
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
Enter fullscreen mode
Exit fullscreen mode
Add picture to XLSX file
package main
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/xuri/excelize/v2"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
defer func() {
// Close the spreadsheet.
if err := f.Close(); err != nil {
fmt.Println(err)
}
}()
// Insert a picture.
if err := f.AddPicture("Sheet1", "A2", "image.png", ""); err != nil {
fmt.Println(err)
}
// Insert a picture to worksheet with scaling.
if err := f.AddPicture("Sheet1", "D2", "image.jpg",
`{"x_scale": 0.5, "y_scale": 0.5}`); err != nil {
fmt.Println(err)
}
// Insert a picture offset in the cell with printing support.
if err := f.AddPicture("Sheet1", "H2", "image.gif", `{
"x_offset": 15,
"y_offset": 10,
"print_obj": true,
"lock_aspect_ratio": false,
"locked": false
}`); err != nil {
fmt.Println(err)
}
// Save the spreadsheet with the origin path.
if err = f.Save(); err != nil {
fmt.Println(err)
}
}
Enter fullscreen mode
Exit fullscreen mode
In this post, you will learn how to read and write Excel files using the Go programming language. For our examples, we will use the xlsx file format.
Golang Excelize
For this guide, we will use the Execlize library to read and write Excel files. It supports file formats, such as xlsx, xlsm, xlam, xltm, and xltx. This package provides methods and API for working with Excel spreadsheets with ease.
To install the package, run the command:
go get github.com/xuri/excelize/v2
Golang Read Excel File
Let us begin by learning how to read an Excel file. Suppose we have an Excel file as shown below:
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/02/echo/Write-Excel-Files-in-Go-1.png» data-lazy- height=»276″ src=»data:image/svg xml,” width=”724″>
To read the values in the Excel file, we can use the following code:
package main
“github.com/xuri/excelize/v2”
)
func main() {
file, err := excelize.OpenFile(“test.xlsx”)
if err != nil {
log.Fatal(err)
}
c1, err := file.GetCellValue(“Sheet1”, “A2”)
if err != nil {
log.Fatal(err)
}
fmt.Println(c1)
c2, err := file.GetCellValue(“Sheet1”, “A3”)
if err != nil {
log.Fatal(err)
}
fmt.Println(c2)
}
The previous example uses the GetCellValue method to get the value of a specified cell. Note that we provide the sheet name and the coordinate of the cell we wish to access as the parameters. The previous program should return the read values as:
Golang Write Excel
We can also create a new Excel file and add a new sheet as shown in the following code example:
package main
import (
“log”
“github.com/xuri/excelize/v2”
)
func main() {
// fmt.Println(c2)
file := excelize.NewFile()
file.SetCellValue(“Sheet1”, “A1”, “Name”)
file.SetCellValue(“Sheet1”, “A2”, “Dulce”)
file.SetCellValue(“Sheet1”, “A3”, “Mara”)
if err := file.SaveAs(“names.xlsx”); err != nil {
log.Fatal(err)
}
}
The previous code creates a new Excel file. We then use the SetCellValue() method to add items to the cells. The method takes the sheet name, cell coordinate, and the value to insert as the parameters.
The previous code should return an Excel file under the name specified in the SaveAs() method.
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/02/echo/Write-Excel-Files-in-Go-2.png» data-lazy- height=»102″ src=»data:image/svg xml,” width=”308″>
Golang Create New Sheet
To create a new sheet to an existing Excel file, we can use the NewSheet() method. An example is shown below:
package main
import (
“fmt”
“log”
“github.com/xuri/excelize/v2”
)
func main() {
file := excelize.NewFile()
idx := file.NewSheet(“Sheet2”)
fmt.Println(idx)
file.SetCellValue(“Sheet2”, “A1”, “Name”)
file.SetCellValue(“Sheet2”, “A2”, “Philip”)
file.SetCellValue(“Sheet2”, “A3”, “Kathleen”)
file.SetActiveSheet(idx)
if err := file.SaveAs(“names.xlsx”); err != nil {
log.Fatal(err)
}
}
The previous code should create a new sheet “Sheete2” in the names.xlsx file. The resulting Excel file should have values as:
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/02/echo/Write-Excel-Files-in-Go-3.png» data-lazy- height=»102″ src=»data:image/svg xml,” width=”360″>
Conclusion
This guide explored the fundamentals of working with Excel files in the Go programming language using the Excelize library. We hope you found this article helpful. Check out other Linux Hint articles for more tips and tutorials.