Introduction

Working with Excel files is a common task in many software projects. Whether you're generating reports or processing data, being able to manipulate Excel files programmatically is essential. In this article, we'll explore how to work with Excel files using the excelize library in the Go programming language.

Installing Excelize

Before we can start working with Excel files, we need to install the excelize library. You can do this by running:

go get github.com/xuri/excelize/v2

Creating an Excel File

Let's start by creating a new Excel file and adding some data to it. Below is a basic example:

package main

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

func main() {
    f := excelize.NewFile()
    // Create a new sheet.
    index := f.NewSheet("Sheet1")
    // Set value of a cell.
    f.SetCellValue("Sheet1", "A1", "Hello")
    f.SetCellValue("Sheet1", "B1", "World")
    // Set active sheet of the workbook.
    f.SetActiveSheet(index)
    // Save the spreadsheet by the given path.
    if err := f.SaveAs("Book1.xlsx"); err != nil {
        fmt.Println(err)
    }
}

Reading from an Excel File

Reading data from an existing Excel file is just as straightforward. Here’s how you can do it:

package main

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

func main() {
    f, err := excelize.OpenFile("Book1.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    // Get value from cell by given worksheet name and cell reference.
    cell, err := f.GetCellValue("Sheet1", "A1")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(cell)
}

Updating an Excel File

Updating existing cells in an Excel file is similar to creating new ones. Here’s an example:

package main

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

func main() {
    f, err := excelize.OpenFile("Book1.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    // Update cell value
    f.SetCellValue("Sheet1", "A1", "Updated Value")
    // Save the file
    if err := f.Save(); err != nil {
        fmt.Println(err)
    }
}

Conclusion

The excelize library provides a simple and effective way to interact with Excel files in Go. This guide covers the basics of creating, reading, and updating Excel files, but there are many more features to explore. For more complex usage and features, you can check the official documentation.