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