Education logo

Step-by-Step Guide to Creating Excel Files with Golang

Unlock the Power of Golang: A Comprehensive Guide to Automating Excel File Creation with Ease

By UniDocPublished 2 years ago 4 min read

Excel files are an integral part of modern data management, widely used for storing, analyzing, and visualizing data. While tools like Microsoft Excel offer a user-friendly interface, developers often need programmatic solutions to generate and manipulate Excel files. Golang (Go), with its simplicity and efficiency, offers robust libraries for this purpose.

For developers seeking robust document processing tools, platforms like UniDoc provide a comprehensive suite of solutions to work with documents in Go, including creating Excel, PDF, and other file formats.

This guide walks you through creating Excel files using Go, specifically leveraging the popular excelize library. By the end of this tutorial, you'll have the skills to create, customize, and save Excel files programmatically.

Why Use Golang for Excel File Creation?

Before diving into the steps, let’s understand why Go is an excellent choice for generating Excel files:

  1. Performance: Go’s concurrency model ensures efficient processing, even for large datasets.
  2. Simplicity: The language's straightforward syntax makes it easy to learn and use.
  3. Cross-Platform: Go binaries work across operating systems, making your solution highly portable.
  4. Rich Ecosystem: Libraries like excelize make handling Excel files seamless.

Prerequisites

To follow this guide, ensure you have the following:

  1. Go Installed: Download and install Go from the official website.
  2. IDE or Text Editor: Use any editor you’re comfortable with, such as VS Code or GoLand.
  3. Excelize Library: Install the excelize library by running:

bash

Copy code

go get github.com/xuri/excelize/v2

Step 1: Setting Up Your Project

Start by creating a Go project. Open your terminal and run:

bash

Copy code

mkdir excel-go-project

cd excel-go-project

go mod init excel-go-project

This initializes a new Go module. Next, install the excelize library as mentioned above.

Step 2: Creating Your First Excel File

The first step is to create a basic Excel file. Let’s write some code to get started.

Code Example: Creating a Simple Excel File

Create a file named main.go and add the following code:

go

Copy code

package main

import (

"fmt"

"github.com/xuri/excelize/v2"

)

func main() {

// Create a new Excel file

f := excelize.NewFile()

// Add data to a cell

sheet := "Sheet1"

f.SetCellValue(sheet, "A1", "Hello, Excel!")

f.SetCellValue(sheet, "A2", "Powered by Golang")

// Save the file

if err := f.SaveAs("example.xlsx"); err != nil {

fmt.Println(err)

} else {

fmt.Println("Excel file created successfully!")

}

}

Explanation:

  1. excelize.NewFile(): Creates a new Excel file.
  2. SetCellValue: Sets the value of a specific cell (e.g., A1).
  3. SaveAs: Saves the file with the specified name (example.xlsx).

Run the program:

bash

Copy code

go run main.go

Check your project directory, and you should see the example.xlsx file.

Step 3: Adding Multiple Sheets

Excel files often contain multiple sheets to organize data effectively. With excelize, you can easily add and name sheets.

Code Example: Adding Sheets

go

Copy code

package main

import (

"fmt"

"github.com/xuri/excelize/v2"

)

func main() {

// Create a new Excel file

f := excelize.NewFile()

// Add a new sheet

sheet2 := "SecondSheet"

index := f.NewSheet(sheet2)

// Write data to the new sheet

f.SetCellValue(sheet2, "A1", "This is the second sheet")

// Set the active sheet

f.SetActiveSheet(index)

// Save the file

if err := f.SaveAs("multi_sheet.xlsx"); err != nil {

fmt.Println(err)

} else {

fmt.Println("Excel file with multiple sheets created successfully!")

}

}

Explanation:

  1. NewSheet: Creates a new sheet and returns its index.
  2. SetActiveSheet: Sets the specified sheet as the active one when the file is opened.

Step 4: Adding Formulas and Styling

Excel files are powerful because of their ability to calculate and present data with styles. Let’s add a formula and some basic styling.

Code Example: Adding Formulas and Styles

go

Copy code

package main

import (

"fmt"

"github.com/xuri/excelize/v2"

)

func main() {

f := excelize.NewFile()

// Add data

sheet := "Sheet1"

f.SetCellValue(sheet, "A1", "Number 1")

f.SetCellValue(sheet, "A2", "Number 2")

f.SetCellValue(sheet, "B1", 10)

f.SetCellValue(sheet, "B2", 20)

// Add a formula

f.SetCellValue(sheet, "B3", "=SUM(B1:B2)")

// Apply styling

style, err := f.NewStyle(`{"font":{"bold":true,"color":"#FF0000"}}`)

if err == nil {

f.SetCellStyle(sheet, "A1", "A2", style)

}

// Save the file

if err := f.SaveAs("styled.xlsx"); err != nil {

fmt.Println(err)

} else {

fmt.Println("Styled Excel file created successfully!")

}

}

Explanation:

  1. SetCellValue: Adds numeric data and a formula.
  2. NewStyle: Creates a style (e.g., bold red text).
  3. SetCellStyle: Applies the style to specified cells.

Step 5: Generating Dynamic Data

In real-world applications, Excel files often contain dynamic data, such as database query results or user input.

Code Example: Generating Dynamic Data

go

Copy code

package main

import (

"fmt"

"github.com/xuri/excelize/v2"

)

func main() {

f := excelize.NewFile()

sheet := "DataSheet"

// Add dynamic data

headers := []string{"ID", "Name", "Age"}

data := [][]interface{}{

{1, "Alice", 25},

{2, "Bob", 30},

{3, "Charlie", 35},

}

// Write headers

for i, header := range headers {

cell := fmt.Sprintf("%c1", 'A'+i)

f.SetCellValue(sheet, cell, header)

}

// Write data

for rowIdx, row := range data {

for colIdx, value := range row {

cell := fmt.Sprintf("%c%d", 'A'+colIdx, rowIdx+2)

f.SetCellValue(sheet, cell, value)

}

}

// Save the file

if err := f.SaveAs("dynamic_data.xlsx"); err != nil {

fmt.Println(err)

} else {

fmt.Println("Excel file with dynamic data created successfully!")

}

}

Step 6: Reading Existing Excel Files

In addition to creating files, excelize allows you to read and extract data from existing Excel files.

Code Example: Reading an Excel File

go

Copy code

package main

import (

"fmt"

"github.com/xuri/excelize/v2"

)

func main() {

// Open an existing file

f, err := excelize.OpenFile("example.xlsx")

if err != nil {

fmt.Println(err)

return

}

// Read data from a cell

cell, err := f.GetCellValue("Sheet1", "A1")

if err != nil {

fmt.Println(err)

return

}

fmt.Println("Data in A1:", cell)

}

Conclusion

With the excelize library, creating and managing Excel files in Golang becomes straightforward and efficient. From adding data and formulas to applying styles and handling dynamic data, you can automate your Excel workflows effortlessly.

This step-by-step guide has shown you how to:

  1. Create and save Excel files.
  2. Add multiple sheets.
  3. Apply formulas and styles.
  4. Generate dynamic content.
  5. Read existing Excel files.

Ready to try it yourself? Dive into Go and explore the full capabilities of excelize to create powerful Excel-based solutions for your projects.

product review

About the Creator

UniDoc

🌐 UniDoc | Simplifying Document Management

At UniDoc, we streamline your document workflow with cutting-edge solutions designed for efficiency and ease.Explore our innovative tools and take control of your documentation today!🔗 Visit Us

Enjoyed the story? Support the Creator.

Subscribe for free to receive all their stories in your feed.

Subscribe For Free

Reader insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment
    Written by UniDoc