GO生成不正确的UTF-8字符,例如ö。

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

GO generate incorrect UTF-8 chars like ö

问题

我正在构建一个Go应用程序,希望通过HTTP服务器从缓冲区输出一个CSV字符串。

我将其放入CSV缓冲区中:

var buffer bytes.Buffer
resp := csv.NewWriter(&buffer)
resp.Write([]string{"Schröder"})

通过HTTP服务器输出:

resp.Flush()
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Write([]byte(buffer.String()))

然后,当我打开我的URL时,一个CSV文件会被下载并在Excel中打开。在Excel表格中,字段值被转换为"Schröder"。

有什么想法吗?我已经在这个问题上卡了一个星期了。

英文:

Ik building an GO application where I want to output a cvs string from a buffer out via the http server.

I'm putting it into the csv buffer:

var buffer bytes.Buffer
resp := csv.NewWriter(&buffer)
resp.Write("Schröder")

The output it via the http server:

resp.Flush()
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Write([]byte(buffer.String()))

When I then open my url a csv file is download en opened by Excel. In that excelsheet the field value is converted to "Schröder".

Any idee, i'm already a week stuk on this item?

答案1

得分: 2

问题不在Go语言中,而是在Excel中。当保存文件时,数据以UTF-8编码的信息丢失了,因为保存的文件上没有编码属性。

因此,Excel只会看到计划数据,并且没有关于编码的信息。有几种技巧可以让Excel正确猜测,比如在文件开头放置正确的字节顺序标记(BOM)。参见是否可以强制Excel自动识别UTF-8 CSV文件?。但是,仅在HTTP的Content-type头中指定charset=utf-8是没有用的,因为Excel不会获取这些信息。

英文:

The problem is not in Go but in Excel. The information that the data are encoded in UTF-8 is lost when saving the file, since there is no such thing as an encoding attribute on saved files.

Thus Excel will just see the plan data and has no information about the encoding. There are several tricks to make Excel do the right guess, like placing the proper byte order mark (BOM) at start of the file. See Is it possible to force Excel recognize UTF-8 CSV files automatically?. But just specifying charset=utf-8 within the HTTP Content-type header will not help since Excel does not get this information.

huangapple
  • 本文由 发表于 2022年2月11日 04:22:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/71071801.html
匿名

发表评论

匿名网友

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

确定