字符编码问题导出数据到CSV

问题描述:

我在rails和某些字段中将数据导出到CSV文件,我在Excel中打开时遇到像这样的字符编码问题:

I'm exporting data to a CSV file in rails and in some of my fields, I'm getting character encoding issues like this when I open in Excel:

didn’t

我假设编码关闭。任何想法应该是什么?

I borrowed this code from an example and I'm assuming the encoding is off. Any idea what it should be?

send_data csv_data,
      :type => 'text/csv; charset=iso-8859-1; header=present',
      :disposition => "attachment; filename=#{filename}.csv"


当Excel打开CSV文件时,它只是假定一个iso-8859-1字符编码。我想它甚至不知道你在HTTP回复中发送的编码信息。这是为什么将此设置为UTF-8不起作用。

When Excel opens the CSV file it just assumes an "iso-8859-1" character encoding. I guess it doesn't even know about the encoding information you send along within your HTTP reply. That's why setting this to UTF-8 doesn't work.

因此,为了在Rails中导出Excel的CSV文件,您可以这样做:

So in order to export your CSV file for Excel in Rails you could do this:

send_data Iconv.conv('iso-8859-1//IGNORE', 'utf-8', csv_data),
  :type => 'text/csv; charset=iso-8859-1; header=present',
  :disposition => "attachment; filename=#{filename}.csv"

这会重新编码您的UTF-8数据字符串(这是Rails默认)到ISO-8859并发送它。沿着这个回复实际上是ISO-8859-1编码的信息(这将不会对Excel有所不同,但在技术上是正确的,如果你应该在浏览器中打开它)。

This re-encodes your UTF-8 data string (that's the Rails default) to ISO-8859 and sends it. Along goes the information that this reply is actually ISO-8859-1 encoded (which won't make a difference for Excel but is technically correct if you should open it in a browser etc.).