Skip to content

Commit

Permalink
add xlsx and mod
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagozs committed Nov 3, 2023
1 parent 567ba73 commit 04770b7
Show file tree
Hide file tree
Showing 6 changed files with 314 additions and 0 deletions.
35 changes: 35 additions & 0 deletions csv/csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package csv

import (
"encoding/csv"
"fmt"
"os"

"github.com/xuri/excelize/v2"
)

type CSV struct{}
Expand Down Expand Up @@ -44,3 +47,35 @@ func (c *CSV) ParseToMap(filePath string) ([]map[string]string, error) {

return records, nil
}

func (c *CSV) ToXLSX(csvFilePath, xlsxFilePath string) error {
csvFile, err := os.Open(csvFilePath)
if err != nil {
return fmt.Errorf("error opening CSV file: %w", err)
}
defer csvFile.Close()

reader := csv.NewReader(csvFile)

records, err := reader.ReadAll()
if err != nil {
return fmt.Errorf("error reading CSV file: %w", err)
}

xlsx := excelize.NewFile()
sheetName := "Sheet1"
xlsx.NewSheet(sheetName)

for i, record := range records {
for j, field := range record {
cell, _ := excelize.CoordinatesToCellName(j+1, i+1)
xlsx.SetCellValue(sheetName, cell, field)
}
}

if err := xlsx.SaveAs(xlsxFilePath); err != nil {
return fmt.Errorf("error saving XLSX file: %w", err)
}

return nil
}
47 changes: 47 additions & 0 deletions csv/csv_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package csv

import (
"os"
"reflect"
"testing"

"github.com/xuri/excelize/v2"
)

func TestParseToMap(t *testing.T) {
Expand Down Expand Up @@ -45,3 +48,47 @@ func TestParseToMap(t *testing.T) {
}
}
}

func TestToXLSX(t *testing.T) {

// Create a temporary file
tmpFile, err := os.CreateTemp("", "test.*.xlsx")
if err != nil {
t.Fatalf("Failed to create temp file: %v", err)
}

c := New()

err = c.ToXLSX("./data/test.csv", tmpFile.Name())
if err != nil {
t.Fatalf("Failed to convert CSV to XLSX: %v", err)
}

xlsx, err := excelize.OpenFile(tmpFile.Name())
if err != nil {
t.Fatalf("Failed to open XLSX file: %v", err)
}

rows, err := xlsx.GetRows("Sheet1")
if err != nil {
t.Fatalf("Failed to get rows from XLSX file: %v", err)
}

if len(rows) != 3 {
t.Fatalf("Expected 2 rows in XLSX file, got %d", len(rows))
}

expected := [][]string{
{"Name", "Age", "City"},
{"Alice", "30", "New York"},
{"Bob", "35", "Los Angeles"},
}

for i, row := range rows {
for j, cell := range row {
if cell != expected[i][j] {
t.Errorf("Expected cell (%d, %d) to be %s, got %s", i, j, expected[i][j], cell)
}
}
}
}
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ require (

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.3 // indirect
github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca // indirect
github.com/xuri/excelize/v2 v2.8.0 // indirect
github.com/xuri/nfp v0.0.0-20230819163627-dc951e3ffe1a // indirect
golang.org/x/crypto v0.12.0 // indirect
golang.org/x/net v0.14.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
61 changes: 61 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,13 +1,74 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM=
github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
github.com/richardlehane/msoleps v1.0.3 h1:aznSZzrwYRl3rLKRT3gUk9am7T/mLNSnJINvN0AQoVM=
github.com/richardlehane/msoleps v1.0.3/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca h1:uvPMDVyP7PXMMioYdyPH+0O+Ta/UO1WFfNYMO3Wz0eg=
github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
github.com/xuri/excelize/v2 v2.8.0 h1:Vd4Qy809fupgp1v7X+nCS/MioeQmYVVzi495UCTqB7U=
github.com/xuri/excelize/v2 v2.8.0/go.mod h1:6iA2edBTKxKbZAa7X5bDhcCg51xdOn1Ar5sfoXRGrQg=
github.com/xuri/nfp v0.0.0-20230819163627-dc951e3ffe1a h1:Mw2VNrNNNjDtw68VsEj2+st+oCSn4Uz7vZw6TbhcV1o=
github.com/xuri/nfp v0.0.0-20230819163627-dc951e3ffe1a/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk=
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
golang.org/x/image v0.11.0/go.mod h1:bglhjqbqVuEb9e9+eNR45Jfu7D+T4Qan+NhQk8Ck2P8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14=
golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
70 changes: 70 additions & 0 deletions xls/xls.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package xls

import (
"encoding/csv"
"fmt"
"os"

"github.com/xuri/excelize/v2"
)

type XLS struct{}

func New() *XLS {
return &XLS{}
}

func (x *XLS) ParseToMap(filePath string) ([]map[string]string, error) {
f, err := excelize.OpenFile(filePath)
if err != nil {
return nil, fmt.Errorf("error opening xlsx file: %w", err)
}
defer f.Close()

rows, err := f.GetRows("Sheet1")
if err != nil {
return nil, fmt.Errorf("error getting rows from xlsx file: %w", err)
}

var records []map[string]string
for _, row := range rows {
record := make(map[string]string)
for i, cell := range row {
record[fmt.Sprintf("col%d", i)] = cell
}

records = append(records, record)
}

return records, nil
}

func (x *XLS) ToCSV(xlsxPath, csvPath string) error {
f, err := excelize.OpenFile(xlsxPath)
if err != nil {
return fmt.Errorf("error opening xlsx file: %w", err)
}
defer f.Close()

rows, err := f.GetRows("Sheet1")
if err != nil {
return fmt.Errorf("error getting rows from xlsx file: %w", err)
}

csvFile, err := os.Create(csvPath)
if err != nil {
return fmt.Errorf("error creating csv file: %w", err)
}
defer csvFile.Close()

writer := csv.NewWriter(csvFile)
defer writer.Flush()

for _, row := range rows {
if err := writer.Write(row); err != nil {
return fmt.Errorf("error writing row to csv file: %w", err)
}
}

return nil
}
93 changes: 93 additions & 0 deletions xls/xls_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package xls

import (
"os"
"reflect"
"testing"

"github.com/xuri/excelize/v2"
)

func TestToCSV(t *testing.T) {
xlsxPath := "./test.xlsx"
csvPath := "./test.csv"

f := excelize.NewFile()
f.SetCellValue("Sheet1", "A1", "Hello")
f.SetCellValue("Sheet1", "B1", "World")
if err := f.SaveAs(xlsxPath); err != nil {
t.Fatalf("Unable to create test xlsx file: %v", err)
}

defer os.Remove(xlsxPath)
defer os.Remove(csvPath)

x := New()

err := x.ToCSV(xlsxPath, csvPath)
if err != nil {
t.Errorf("ToCSV() error = %v", err)
}

if _, err := os.Stat(csvPath); os.IsNotExist(err) {
t.Errorf("CSV file was not created")
}

}

func TestParseToMap(t *testing.T) {
xlsxPath := "./testp.xlsx"
sheetName := "Sheet1"

f := excelize.NewFile()

f.NewSheet(sheetName)
f.SetCellValue(sheetName, "A1", "Header1")
f.SetCellValue(sheetName, "B1", "Header2")
f.SetCellValue(sheetName, "A2", "Value1")
f.SetCellValue(sheetName, "B2", "Value2")

if err := f.SaveAs(xlsxPath); err != nil {
t.Fatalf("Unable to create test xlsx file: %v", err)
}

defer func() {
err := f.Close()
if err != nil {
t.Fatalf("Unable to close the xlsx file: %v", err)
}
err = os.Remove(xlsxPath)
if err != nil {
t.Fatalf("Unable to remove the xlsx file: %v", err)
}
}()

expected := []map[string]string{
{"col0": "Header1", "col1": "Header2"},
{"col0": "Value1", "col1": "Value2"},
}

x := New()

records, err := x.ParseToMap(xlsxPath)
if err != nil {
t.Errorf("ParseToMap() error = %v", err)
}

if !reflect.DeepEqual(records, expected) {
t.Errorf("ParseToMap() got = %v, want %v", records, expected)
}
}

func TestParseToMapError(t *testing.T) {
// Non-existent file path
xlsxPath := "./nonexistent.xlsx"

// Execute the function to test.
x := New()

_, err := x.ParseToMap(xlsxPath)
if err == nil {
t.Errorf("ParseToMap() expected error, got nil")
}
}

0 comments on commit 04770b7

Please sign in to comment.