Gorm Model to Csv Output

This sample works in perfect
func GenerationCSV(c *gin.Context) {
	items := [][]string{
			{"UserID", "FullName", "Email"},           // Header
			{"1", "Jack Johnson", "jack@hotmail.com"}, // Items
			{"2", "Jill Smith", "jill@hotmail.com"},
			{"3", "James Murphy", "james@hotmail.com"},
		}
	// Set our headers so browser will download the file
	c.Header("Content-Type", "text/csv")
	c.Header("Content-Disposition", "attachment;filename=users.csv")
	// Create a CSV writer using our HTTP response writer as our io.Writer
	wr := csv.NewWriter(c.Writer)

	if err := wr.WriteAll(employees); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to generate CSV file",
		})
		return
	}
}

But when using this code I have a compiled error where

package models

import "gorm.io/gorm"

type Employee struct {
	gorm.Model
	Firstname   string  `json:"first_name"`
	Lastname    string  `json:"last_name"`
	Email       string  `json:"email"`
	Gender      string  `json:"gender"`
	Ipaddress   string  `json:"ip_address"`
	Avatar      string  `json:"avatar"`
	Phone       string  `json:"phone"`
	Latitude    float64 `json:"latitude"`
	Longitude   float64 `json:"longitude"`
	Password    string  `json:"password"`
	Socialmedia string  `json:"social_media"`
}

And CSV generation failed

func GenerationCSV(c *gin.Context) {
	fmt.Println("Start")
	//Get all users
	var employees []models.Employee
	initializers.DB.Find(&employees)
	// Set our headers so browser will download the file
	c.Header("Content-Type", "text/csv")
	c.Header("Content-Disposition", "attachment;filename=users.csv")
	// Create a CSV writer using our HTTP response writer as our io.Writer
	wr := csv.NewWriter(c.Writer)

	if err := wr.WriteAll(employees); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to generate CSV file",
		})
		return
	}

	fmt.Println("Step------------->")
	fmt.Println("Stop")
}

Any help cause this expects an [][]string

// WriteAll writes multiple CSV records to w using Write and then calls Flush,

// returning any error from the Flush.

func (w *Writer) WriteAll(records [][]string) error

Hi @Maodo_Diop ,

To start debuting this, I would first check these items:

  1. Does initializers.DB.Find() return an error value? If so, check this return value for a non-nil error.

  2. Does initializers.DB.Find() actually fill the employee variable?

  3. What error does wr.WriteAll(employees) return?

These checks should help narrow down the root cause.

Hi

Step 1 & 2 are ok but I have a compiler problem in VsCode like this : *cannot use &employees (value of type []models.Employee) as [][]string value in argument to wr.WriteAllcompilerIncomp
FYI : I have implemented all crud to the given Model models.Employees

In the conole with hot reload I have this : 2022/07/28 19:46:39 Running build command!
2022/07/28 19:46:42 Error while building:

go-jwwt/viz

*viz\generatorFile.go:25:24: cannot use &employees (type []models.Employee) as type [][]string in argument to wr.WriteAll

I create a variable and looping over this from the employees.

wr := csv.NewWriter(c.Writer)
	//Expected data format : Here the Solution
	var data [][]string
	for _, record := range employees {
		row := []string{
			record.Firstname,
			record.Lastname,
			record.Email,
			record.Gender,
			record.Ipaddress,
			record.Avatar,
			record.Phone,
			strconv.FormatFloat(record.Latitude, 'f', -1, 64),
			strconv.FormatFloat(record.Longitude, 'f', -1, 64),
			record.Password,
			record.Socialmedia,
		}
		data = append(data, row)
	}

	if err := wr.WriteAll(data); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to generate CSV file",
		})
		return
	}
1 Like

Ah, ok. Sorry, I missed the fact that it is a compiler error. Glad to see you were able to solve it.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.