英文:
Keep the leading zeros of a string when exporting to CSV in Golang
问题
我有一个使用Gin框架的Go应用程序,它将一个结构体导出为CSV文件。其中一个列 userCode 需要保留字符串中的所有前导零。
例如,对于字符串 000001、010101、000000,在CSV中导出的字段应该具有完全相同的值。然而,如果我直接将字符串附加到行并写入缓冲区,导出的字段将会省略所有前导零,值变为:1、10101、 。我进行了一些调查,似乎可以通过在读取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)
}
英文:
-
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)}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论