在Golang中将字符串导出为CSV时保留前导零。

huangapple go评论87阅读模式
英文:

Keep the leading zeros of a string when exporting to CSV in Golang

问题

我有一个使用Gin框架的Go应用程序,它将一个结构体导出为CSV文件。其中一个列 userCode 需要保留字符串中的所有前导零。

例如,对于字符串 000001010101000000,在CSV中导出的字段应该具有完全相同的值。然而,如果我直接将字符串附加到行并写入缓冲区,导出的字段将会省略所有前导零,值变为:110101 。我进行了一些调查,似乎可以通过在读取CSV文件时在Excel中设置列类型来解决这个问题,但我想知道是否可以在Go程序中解决这个问题?谢谢!

我的CSV导出相关函数:

func (h *HandleManager) ExportUsers() gin.HandlerFunc {

        var buf bytes.Buffer
		writer := csv.NewWriter(&buf)
		var cols = []string{"用户名", ..., ....}
		writer.Write(cols)
        for _, e := range users {
            var row []string
            // ....
            row = append(row, e.userCode) // 类型: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())
}

请注意,我只翻译了您提供的代码部分。

英文:

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

答案1

得分: 1

经过几次尝试,我找到了在golang中有效的解决方案,感谢@Steffen Ullrich提供的链接。与在VB中有效的解决方案类似,只需要在两侧使用一个引号即可,而不是两个引号:

row = append(row, "=\"" + e.userCode + "\"")

这样在CSV文件中将包含所有前导零:

000001, 010101, 000000
英文:

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

答案2

得分: 1

我测试了你的代码,结果在Excel中会丢失零,但在文本阅读器中不会丢失。

代码:

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)

}

结果:
在Golang中将字符串导出为CSV时保留前导零。

英文:
  1. I tested your code, and the result in excel would loss the zeros, but in txt reader would not;

  2. 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)
    

    }

result:
在Golang中将字符串导出为CSV时保留前导零。

huangapple
  • 本文由 发表于 2022年5月27日 12:58:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/72400640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定