如何修复Rails导出的Excel(.xls)文件中的字符编码



我正在使用一个控制器,该控制器导出一个.xls文件,该文件包含几个包含西班牙语翻译文本的字段。

字符编码似乎关闭了,因为文件中到处都是像Débito Automático而不是Débito Automático这样的单词。

我认为excel默认为iso-8859-1字符编码,但我不知道如何从Rails控制器更改或指定它。

def show
...
format.xls do
@enriched_invoices = @enriched_invoices.includes(user: { address: :city })
end
end
end
end

响应.xls格式的html:

<table border="1">
<tr>
<th>Fecha Factura</th>
<th>ID Cliente</th>
<th>user_external_reference</th>
<th>Cliente</th>
<th>Domicilio</th>
<th>Código Postal</th>
<th>Ciudad</th>
<th>DNI</th>
<th>Email</th>
<th>ID Factura</th>
<th>Motivo</th>
<th>Descripción</th>
<th>Estado</th>
<th>Importe del Recibo</th>
<th>Metodo de pago</th>
<th>Estado Ultimo Pago</th>
<th>Descripcion estado Ultimo Pago</th>
<th>Fecha de creación del Pago</th>
<th>Fecha de aprobación del Pago</th>
<th>Monto del pago</th>
<th>Forma de pago</th>
</tr>
<% @enriched_invoices.each do |invoice| %>
<tr>
<td><%= invoice.due_date.strftime("%Y-%m-%d") %></td>
<td><%= invoice.user_id %></td>
<td><%= invoice.user.external_reference %></td>
<td><%= invoice.user.full_name %></td>
<td><%= invoice.user.address&.full_address %></td>
<td><%= invoice.user.address&.cp %></td>
<td><%= invoice.user.address&.city_name.presence || invoice.user.address&.city&.name %></td>
<td><%= invoice.user.doc_number %></td>
<td><%= invoice.user.email %></td>
<td><%= invoice.id %></td>
<td><%= invoice.subscription? ? 'Subscription' : invoice.invoiceable_type %></td>
<td><%= invoice.invoice_items.order(:id).pluck(:description).join('. ') %></td>
<td><%= invoice.status %></td>
<td><%= humanized_money_with_symbol invoice.amount %></td>
<td><%= invoice.payment_method %></td>
<td><%= invoice.last_payment_status %> </td>
<td><%= invoice.last_payment_status_detail %> </td>
<td><%= invoice.last_payment_date_created&.strftime("%Y-%m-%d") %> </td>
<td><%= invoice.last_payment_date_approved&.strftime("%Y-%m-%d") %> </td>
<td><%= humanized_money_with_symbol(Money.new(invoice.last_payment_amount_cents, invoice.amount.currency)) %></td>
<td><%= invoice.last_payment_payment_type %></td>
</tr>
<% end %>
</table>

有没有办法在没有宝石的情况下做到这一点?

您可能可以用其中一种方法(通过增加工作的可能性(解决

  1. 使用特定的响应布局,明确声明内容为UTF-8。不能保证Excel会答应,而且无论如何也没有任何关于它的文档。

  2. 强制渲染管道使用:xls格式的特定选项。检查https://api.rubyonrails.org/classes/ActionController/Renderers.html#method-c-添加

  3. 将您的数据显示为CSV(同样不能保证excel正确解析(

  4. 使用html实体代替utf-8字节序列:"Descripci&oacute;n"或也使用https://rubygems.org/gems/htmlentities和HTMLEntities.new.encode(string, :named),如果您在代码(而不是模板(中有内容

最新更新