Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Monday, December 12, 2022

Create Excel File in Go


 

In the following post we will wrap Excel file creation in GO.

The excel wraps the Excelize library, and simplify the usage for applications, that need a simple excel. This is not suitable for complex excel sheets.


Upon creation of the wrapper, we create a new excel file, with some default styles.


package excel2

import (
"fmt"
"github.com/xuri/excelize/v2"
)

const sheetName = "Sheet1"

type Excel struct {
excelFile *excelize.File
currentRow int
currentColumn int
styleBold int
styleRed int
styleOrange int
styleNormal int
}

func ProduceExcel() *Excel {
excelFile := excelize.NewFile()

const fontSize = 10
styleBold, err := excelFile.NewStyle(&excelize.Style{
Font: &excelize.Font{
Bold: true,
Family: "Times New Roman",
Size: fontSize,
Color: "#000000",
},
})
if err != nil {
panic(err)
}

styleRed, err := excelFile.NewStyle(&excelize.Style{
Font: &excelize.Font{
Bold: true,
Family: "Times New Roman",
Size: fontSize,
Color: "#FF0000",
},
})
if err != nil {
panic(err)
}

styleOrange, err := excelFile.NewStyle(&excelize.Style{
Font: &excelize.Font{
Bold: false,
Family: "Times New Roman",
Size: fontSize,
Color: "#FFA500",
},
})
if err != nil {
panic(err)
}

styleNormal, err := excelFile.NewStyle(&excelize.Style{
Font: &excelize.Font{
Bold: false,
Family: "Times New Roman",
Size: fontSize,
Color: "#000000",
},
})
if err != nil {
panic(err)
}

err = excelFile.SetColWidth(sheetName, "A", "Z", 30)
if err != nil {
panic(err)
}

return &Excel{
excelFile: excelFile,
currentRow: 1,
currentColumn: -1,
styleBold: styleBold,
styleRed: styleRed,
styleOrange: styleOrange,
styleNormal: styleNormal,
}
}



Next we handle add of data to the excel:



func (e *Excel) MoveToNextRow() {
e.currentRow++
e.currentColumn = -1
}

func (e *Excel) AddNextCell(text string) {
e.currentColumn++

axis := e.getCurrentCellAxis()
err := e.excelFile.SetCellValue(sheetName, axis, text)
if err != nil {
panic(err)
}
}

func (e *Excel) getCurrentCellAxis() string {
columnChar := string(rune(int('A') + e.currentColumn))
axis := fmt.Sprintf("%v%v", columnChar, e.currentRow)
return axis
}



And provide a simple style wrapper:


func (e *Excel) SetCellStyle(bold bool, red bool, orange bool) {
axis := e.getCurrentCellAxis()
if bold {
err := e.excelFile.SetCellStyle(sheetName, axis, axis, e.styleBold)
if err != nil {
panic(err)
}
} else if red {
err := e.excelFile.SetCellStyle(sheetName, axis, axis, e.styleRed)
if err != nil {
panic(err)
}
} else if orange {
err := e.excelFile.SetCellStyle(sheetName, axis, axis, e.styleOrange)
if err != nil {
panic(err)
}
} else {
err := e.excelFile.SetCellStyle(sheetName, axis, axis, e.styleNormal)
if err != nil {
panic(err)
}
}
}


Last, we can save the file:



func (e *Excel) SaveAs(filePath string) {
err := e.excelFile.SaveAs(filePath)
if err != nil {
panic(err)
}
}





No comments:

Post a Comment