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())
}
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