I have a Go application using Gin framework that exports a struct to CSV. One column userCode
requires the exported field keeping all the leading zeros of the string.
For example, for string such as 000001
, 010101
, 000000
, the exported field in CSV should have the exact similar value. However, if I directly append the string to the row and write to the buffer, the exported field will emit all the leading zeros and the value becomes: 1
, 10101
,
, I did some digging and it seems this problem can be fixed by setting column type in Excel when reading the csv file, but I was wondering if this can be solved within Go program? Thanks!
My CSV export related function:
func (h *HandleManager) ExportUsers() gin.HandlerFunc {
var buf bytes.Buffer
writer := csv.NewWriter(&buf)
var cols = []string{"User Name", ..., ....}
writer.Write(cols)
for _, e := range users {
var row []string
// ....
row = append(row, e.userCode) // type: string
if err := writer.Write(row); err != nil {
log.Errorff(h.logCtx, "ExportUsers|WriteToCSV|err:%v", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
}
writer.Flush()
c.Writer.Header().Set("Content-Type", "text/csv")
c.Writer.Header().Set("Content-Disposition", "attachment;filename=" csvFileName ".csv")
c.Writer.Write(buf.Bytes())
}
CodePudding user response:
After a few tries I found the solution that worked in golang,thanks to the link @Steffen Ullrich posed. Similar to which worked in VB, instead of two quotation marks on both sides, one should be enough:
row = append(row, "=\"" e. userCode "\"")
will contain all the leading zeros in the CSV file:
000001, 010101, 000000
CodePudding user response:
I tested your code, and the result in excel would loss the zeros, but in txt reader would not;
code:
func main() { type user struct { Name string Code string }
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { var buf bytes.Buffer writer := csv.NewWriter(&buf) var cols = []string{"Name", "Code"} writer.Write(cols) users := []user{{Name: "Tome", Code: "001"}, {Name: "James", Code: "000"}} for _, e := range users { err := writer.Write([]string{e.Name, e.Code}) if err != nil { log.Fatalln(err) } } writer.Flush() w.Header().Set("Content-Type", "text/csv") w.Header().Set("Content-Disposition", "attachment;filename=" "test.csv") w.Write(buf.Bytes()) }) http.ListenAndServe(":8080", nil)
}