How to Convert a CSV File to XLSX in Go
When working with data sets, CSV and XLSX are two of the most widely used file formats, with each offering their own benefits. However, Excel is the preferable format when needing to share a file with a customer or partner, as it has wider support across programs than CSV. The following API will convert any CSV file to XLSX instantly; if you have frequently have CSV files that need converting, this can save you a significant amount of time.
To call the conversion function, simply input your CSV file and API key into the below code:
package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)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))
}
And just like that, your Excel file will be ready to go! If you need to obtain an API key, you can do so by registering for a free account on the Cloudmersive website; this provides 800 monthly calls across our multitude of APIs.