解释来自Mac Excel 2011的Sinatra中的非拉丁字符

问题描述 投票:1回答:3

我有一个Mac VBA脚本向Ruby Sinatra Web应用程序发出请求。

从Excel传递的文本包含é等字符。 Ruby(版本1.9.2)对这些字符进行了扼流,因为Excel不会将它们作为UTF-8发送。

# encoding: utf-8
require 'rubygems'

require 'sinatra'
require "sinatra/reloader" if development?

configure do
  class << Sinatra::Base
    def options(path, opts={}, &block)
      route 'OPTIONS', path, opts, &block
    end
  end
  Sinatra::Delegator.delegate :options
end

options '/' do
  response.headers["Access-Control-Allow-Origin"] = "*"
  response.headers["Access-Control-Allow-Methods"] = "POST"

  halt 200
end

post '/fetch' do
  chars = []
  params['excel_input'].valid_encoding?  #returns false
  params['excel_input']
end

我的Excel VBA:

Sub FetchAddress()
    For Each oDest In Selection
        With ActiveSheet.QueryTables.Add(Connection:="URL;http://localhost:4567/fetch", Destination:=oDest)
            .PostText = "excel_input=" & oDest.Offset(0, -1).Value
            .RefreshStyle = xlOverwriteCells
            .SaveData = True
            .Refresh
        End With
    Next
End Sub

角色é作为Ž出现在另一端。

看起来Excel中的文本被编码为Windows-1252 http://en.wikipedia.org/wiki/Windows-1252

字符的字节表示为142(或Windows-1252中的Ž)。

ruby character-encoding excel-vba sinatra vba
3个回答
1
投票

iconv可以将输入转换为UTF-8。它将字符编码从一种编码转换为另一种编码。所以像这样的东西应该工作:

require "iconv"
...
post '/fetch' do
  excel_input = Iconv.conv("UTF-8", "WINDOWS-1252", params['excel_input'])
  ...
end

1
投票

您也可以查看:https://github.com/jmhodges/rchardet然后,您可以自动检测字符集,然后将其转换为utf-8。


0
投票

Ruby 1.9 Encodings: A Primer and the Solution for Rails - yehuda katz读起来不错。如果你有时间。深入了解编码以及如何在它们之间进行转换。

© www.soinside.com 2019 - 2024. All rights reserved.