将 jruby 1.8 字符串转换为 windows 编码?
我想将 jruby on Rails webapp 中的一些数据导出到 Excel,因此我创建一个 csv 字符串并将其作为下载发送到客户端,使用
send_data(text, :filename => "file.csv", :type => "text/csv; charset=CP1252", :encoding => "CP1252")
该文件似乎采用 UTF-8 格式,Excel 无法正确读取。我用谷歌搜索了这个问题,发现 iconv 可以转换编码。我尝试这样做:
ic = Iconv.new('CP1252', 'UTF-8')
text = ic.iconv(text)
但是当我发送转换后的文本时,它没有任何区别。它仍然是UTF-8,Excel无法读取特殊字符。有多种使用 iconv 的解决方案,因此这似乎对其他人也适用。当我使用 iconv 在 linux shell 上手动转换文件时,它可以工作。
我做错了什么?有更好的办法吗?
我正在使用: - jruby 1.3.1 (ruby 1.8.6p287) (2009-06-15 2fd6c3d) (Java HotSpot(TM) 客户端 VM 1.6.0_19) [i386-java] - 黛安·莱尼 - Glassfish 应用服务器 - Iceweasel 3.0.6
编辑: 我是否必须包含一些 gem 才能使用 iconv?
解决方案: S.Mark指出了这个解决方案: 您必须使用 UTF-16LE 编码才能使 Excel 理解它,如下所示:
text= Iconv.iconv('UTF-16LE', 'UTF-8', text)
谢谢 S.Mark 的回答。
I want to export some data from my jruby on rails webapp to excel, so I create a csv string and send it as a download to the client using
send_data(text, :filename => "file.csv", :type => "text/csv; charset=CP1252", :encoding => "CP1252")
The file seems to be in UTF-8 which Excel cannot read correctly. I googled the problem and found that iconv can convert encodings. I try to do that with:
ic = Iconv.new('CP1252', 'UTF-8')
text = ic.iconv(text)
but when I send the converted text it does not make any difference. It is still UTF-8 and Excel cannot read the special characters. there are several solutions using iconv, so this seems to work for others. When I convert the file on the linux shell manually with iconv it works.
What am I doing wrong? Is there a better way?
Im using:
- jruby 1.3.1 (ruby 1.8.6p287) (2009-06-15 2fd6c3d) (Java HotSpot(TM) Client VM 1.6.0_19) [i386-java]
- Debian Lenny
- Glassfish app server
- Iceweasel 3.0.6
Edit:
Do I have to include some gem to use iconv?
Solution:
S.Mark pointed out this solution:
You have to use UTF-16LE encoding to make excel understand it, like this:
text= Iconv.iconv('UTF-16LE', 'UTF-8', text)
Thanks, S.Mark for that answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据我的经验,Excel无法正确处理UTF-8 CSV文件。尝试使用 UTF-16 代替。
注意:Excel 的导入文本向导似乎也可以使用 UTF-8
编辑:在 Stack Overflow 上搜索可以找到 此页面,请看一下。
据此,在 CSV 中添加 BOM(字节顺序标记)签名将弹出 Excel 文本导入向导,因此您可以使用它作为解决方法。
According to my experience, Excel cannot handle UTF-8 CSV files properly. Try UTF-16 instead.
Note: Excel's Import Text Wizard appears to work with UTF-8 too
Edit: A Search on Stack Overflow give me this page, please take a look that.
According to that, adding a BOM (Byte Order Mark) signature in CSV will popup Excel Text Import Wizard, so you could use it as work around.
您是否会得到与以下相同的结果?
Do you get the same result with the following?