adding excel2struct

This commit is contained in:
2024-10-17 20:59:36 +02:00
parent 254b2ce0f3
commit 4e355106ff
6 changed files with 0 additions and 87 deletions
Binary file not shown.
+36
View File
@@ -0,0 +1,36 @@
# excel2struct
Convierte una hoja de excel compatible con la librería [Excelize](https://github.com/qax-os/excelize) a un tipo estructurado de Go. La primera fila debe coincidir con la etiqueta XLSX, sensible a las mayúsculas.
| Id | Nombre | Apellidos | Email | Género | Balance |
|----|--------|-----------|--------------------------|--------|---------|
| 1 | Caryl | Kimbrough | ckimbrough0@fotki.com | true | 571.08 |
| 2 | Robin | Bozward | rbozward1@thetimes.co.uk | true | 2162.89 |
| 3 | Tabbie | Kaygill | tkaygill2@is.gd | false | 703.94 |
```go
type User struct {
Id int `xlsx:"Id"`
Name string `xlsx:"Nombre"`
LastName string `xlsx:"Apellidos"`
Email string `xlsx:"Email"`
Gender bool `xlsx:"Género"`
Balance float32 `xlsx:"Balance"`
}
```
```go
func main() {
data := exceltostruct.Convert[User]("Book1.xlsx", "Sheet1")
fmt.Println(data)
}
```
```bash
[{1 Caryl Kimbrough ckimbrough0@fotki.com true 571.08} {2 Robin Bozward rbozward1@thetimes.co.uk true 2162.89} {3 Tabbie Kaygill tkaygill2@is.gd false 703.94}]
```
Donde el primer parámetro es la ruta donde está ubicada la hoja de cálculo y la segunda el nombre de la hoja.
Tipos compatibles: **int**, **float32**, **bool** y **string**.
+63
View File
@@ -0,0 +1,63 @@
package exceltostruct
import (
"github.com/xuri/excelize/v2"
"reflect"
"strconv"
)
func Convert[T any](bookPath, sheetName string) (dataExcel []T) {
f, _ := excelize.OpenFile(bookPath)
rows, _ := f.GetRows(sheetName)
firstRow := map[string]int{}
for i, row := range rows[0] {
firstRow[row] = i
}
t := new(T)
dataExcel = make([]T, 0, len(rows)-1)
for _, row := range rows[1:] {
v := reflect.ValueOf(t)
if v.Kind() == reflect.Pointer {
v = v.Elem()
}
for i := 0; i < v.NumField(); i++ {
tag := v.Type().Field(i).Tag.Get("xlsx")
objType := v.Field(i).Type().String()
if j, ok := firstRow[tag]; ok {
field := v.Field(i)
if len(row) > j {
d := row[j]
elementConverted := convertType(objType, d)
field.Set(reflect.ValueOf(elementConverted))
}
}
}
dataExcel = append(dataExcel, *t)
}
return dataExcel
}
func convertType(objType string, value string) any {
switch objType {
case "int":
valueInt, _ := strconv.Atoi(value)
return valueInt
case "bool":
valueBool, _ := strconv.ParseBool(value)
return valueBool
case "float32":
valueFloat, _ := strconv.ParseFloat(value, 32)
return float32(valueFloat)
case "string":
return value
}
return value
}