Write data to an Excel file in Golang

Post on: 2023-06-06 23:01:14 | in: Golang
To write data to an Excel file in Golang, you can use the "github.com/tealeg/xlsx" package. Here's an example of how to create a new Excel file and write data to it
package main

import (
    "log"

    "github.com/tealeg/xlsx"
)

func main() {
    // Create a new Excel file
    file := xlsx.NewFile()

    // Add a new sheet to the Excel file
    sheet, err := file.AddSheet("Sheet1")
    if err != nil {
        log.Fatal(err)
    }

    // Create a row and add data to it
    row := sheet.AddRow()
    cell := row.AddCell()
    cell.Value = "Name"

    cell = row.AddCell()
    cell.Value = "Age"

    // Add more rows and data
    row = sheet.AddRow()
    cell = row.AddCell()
    cell.Value = "John"

    cell = row.AddCell()
    cell.SetInt(30)

    row = sheet.AddRow()
    cell = row.AddCell()
    cell.Value = "Jane"

    cell = row.AddCell()
    cell.SetInt(25)

    // Save the Excel file
    err = file.Save("output.xlsx")
    if err != nil {
        log.Fatal(err)
    }
}

In this example, we import the "github.com/tealeg/xlsx" package and create a new Excel file using xlsx.NewFile(). We then add a new sheet to the file with the name "Sheet1" using file.AddSheet().

Next, we create rows and cells to store data. Each cell's value is set using the cell.Value property. You can set various types of values such as strings, integers, floats, dates, etc. In this example, we add a header row with "Name" and "Age" and two rows with sample data.

Finally, we save the Excel file using file.Save(), specifying the output file path as "output.xlsx".

Make sure to import the necessary package (github.com/tealeg/xlsx) and customize the code according to your data and requirements.