How to Convert CSV to Excel XLSX in Go

Cloudmersive
2 min readJun 3, 2024

--

If we’re looking for an easy, reliable way to convert CSV data to Excel Go, we can simply lean on a free data conversion API.

This way, we won’t need to write a bunch of new code to handle our data conversions. Our requests containing CSV file uploads will receive a response with Excel XLSX file encoding, which we can then write to a new file and save in a relevant location.

To structure our API call, we can use the ready-to-run Go code examples provided below. Other than that, we’ll just need a free API key to authorize our requests (this will allow us to make up to 800 API calls per month with no additional commitments).

First, let’s declare our Go file and add our imports:

package main

import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)

Next, let’s use the remaining code to call our conversion function (this performs an HTTP POST request to the URL with multipart/form-data). After we upload our file, we can replace “YOUR-API-KEY-HERE” with our own free API key string:

func main() {

url := "https://api.cloudmersive.com/convert/csv/to/xlsx"
method := "POST"

payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("inputFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}


client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)

if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")

req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()

body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}

In the above code, error messages are printed to the console. To enhance error handling in our own application, we can return errors to the caller, log errors for debugging, or pass errors up the call stack when necessary.

That’s all there is to it — now we can easily convert our CSV files to Excel XLSX in Go.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.