If you’ve ever worked with spreadsheets and wanted to programmatically create or manipulate Excel files using Go, Excelize is the tool for you! This blog will walk you through the essentials of using the Excelize library, from installation to advanced features such as adding charts and images. Let’s dive in!
Introduction to Excelize
Excelize is a powerful library written in pure Go that enables developers to read from and write to various Excel file formats, including XLSX, XLSM, XLTX, and more. It’s designed for high compatibility and provides a streaming API for handling substantial amounts of data efficiently. Before you begin, ensure that you are running Go version 1.18 or later, and beware of minor issues if you are on Go 1.21.0.
Installation
To install Excelize, use the following command:
go get github.com/xuri/excelize/v2
If you’re using Go Modules, the same command will apply. You’re now set to use Excelize in your Go projects!
Creating a Spreadsheet
Creating a spreadsheet is as easy as pie! Here’s a minimal example that demonstrates how to create a new Excel 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 from a Spreadsheet
Reading from a spreadsheet is just as simple. Below is an example demonstrating how to retrieve and print cell values from an Excel file:
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() {
if err := f.Close(); err != nil {
fmt.Println(err)
}
}()
// Get value from cell
cell, err := f.GetCellValue("Sheet1", "B2")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(cell)
// Get all rows in 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()
}
}
Adding a Chart to Your Spreadsheet
Charting in Excelize can be done with just a few lines of code. Here’s how you can add a 3D clustered column chart:
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",
},
// Add more series as needed
},
Title: []excelize.RichTextRun{
{Text: "Fruit 3D Clustered Column Chart"},
},
}); err != nil {
fmt.Println(err)
return
}
// Save spreadsheet
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
Inserting Pictures into the Spreadsheet
Excelize also allows you to add images to your Excel files easily. Here’s how you can insert different types of images:
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() {
if err := f.Close(); err != nil {
fmt.Println(err)
}
}()
// Insert images with scaling and printing support
if err := f.AddPicture("Sheet1", "A2", "image.png", nil); err != nil {
fmt.Println(err)
}
if err := f.AddPicture("Sheet1", "D2", "image.jpg",
excelize.GraphicOptions{ScaleX: 0.5, ScaleY: 0.5}); err != nil {
fmt.Println(err)
}
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
if err := f.Save(); err != nil {
fmt.Println(err)
}
}
Troubleshooting
If you encounter any issues while using Excelize, here are some troubleshooting suggestions:
- Ensure you have the corresponding version of Go installed (1.18 or higher).
- If you run into compatibility issues, consider upgrading to Go version 1.21.1 or later.
- Double-check your Excel file paths for any typos or incorrect directories.
- If you still experience problems, consult the detailed documentation on go.dev or the docs reference.
For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.
Conclusion
Excelize is a robust library that simplifies the process of working with Excel files in Go. Whether you are creating a spreadsheet, reading existing data, or adding rich content like charts and images, Excelize has got you covered. At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.
Contributing
Contributions are always welcome! If you find a bug or have suggestions for new features, feel free to open a pull request or issue on GitHub.
Licenses
This program is licensed under the terms of the BSD 3-Clause License. For details, refer to the license page.