Rails4数据表导出到excel文件正在运行,但文件不可读



由于某些原因,使用以下代码生成的excel只能在开发和暂存模式下工作。在生产服务器中,如果在生产模式下生成,则使用数据表生成的excel文件不起作用,并显示警告"excel无法打开xyz.xlsx,因为某些内容不可读"。我使用的是数据表1.10.18。

application.js

//= require datatables/datatables.min.js
//= require datatables/moment.js
//= require datatables/datetime-moment.js
//= require datatables/datatables_setup.js

HTML:

<table id="store_orders_table" class="table table-stripped">
<thead>
<tr>
<th class="bold-detail-text">Customer</th>
<th class="bold-detail-text">Order Items</th>
<th class="bold-detail-text">Order Date</th>
<th class="bold-detail-text">Payment Method</th> 
</tr>
</thead>
<tbody>
<% @orders && @orders.each_with_index do |order,index| %> 
<tr>
<td class="detail-text">
<%= order.name rescue "" %>
</td>
<td class="detail-text" style="min-width:102px;">
<%= order.order_item.name %>
</td>
<td class="detail-text" data-export="<%= order.payment.payment_date.strftime("%m-%d-%Y") %>"> 
<%= order.payment.payment_date.strftime("%B %d, %Y") rescue ""%>
</td>
<td class="detail-text">
<%= order.payment.payment_method.to_s.titleize rescue "" %>
</td> 
<td class="detail-text">
<%=order.comments %>
</td>
</tr>
<% end %>
</tbody>
<tfoot>
</tfoot>
</table>

JS:

$('#store_orders_table').DataTable( {
"language": {
"emptyTable": "<i class='detail-text'>No records found</i>"
},
pageLength: 100,
bFilter: true,
dom: 'Brtipl',
"order": [[ 2, "desc" ]],
buttons: [
{
extend: 'excelHtml5',
filename: 'store_orders_report',
title: "",
footer: false,
header: true,
text: '<i class="fa fa-file-excel-o"></i> Export as Excel',
titleAttr: 'Export as EXCEL',
classAttr: 'pull-right', 
exportOptions: { 
orthogonal: 'export', 
columns: [0,1,2,3], 
format: {
body: function ( data, row, column, node ) {
if( typeof $(node).data('export') !== 'undefined'){
data = $(node).data('export');
}                 
return data;
}              
}
}
}
],
columns: [
{ data: "0",render: function (data, type, row) { return data }},
{ data: "1",render: function (data, type, row) { return data }},
{ data: "2",render: function (data, type, row) { return data }},
{ data: "3",render: function (data, type, row) { return data }}, 
],
"columnDefs": [
{"targets": [ 0 ], "visible": true, "searchable": true },
{"targets": [ 1 ], "visible": true, "searchable": true },
{"targets": [ 2 ], "visible": true, "searchable": true },
{"targets": [ 3 ], "visible": true, "searchable": true }, 
]
}); 

在这里发布答案,因为我在任何地方都没有发现它的文档。花了几个小时后,它在production.rb中更改了js_compressor。在预编译资产时,数据表似乎也需要对ES5/ES6的支持。excel现在可以显示所有类型的字符,包括对其他语言字符的支持。此前,由于特殊字符&一些日语内容。

# Compress JavaScripts
#config.assets.js_compressor = :uglifier
config.assets.js_compressor = Uglifier.new(harmony: true)  

您可以使用data.replace(/</?[^>]+(>|$)/g, "");清除html条形标签

exportOptions: {
format: {
body: function(data, row, column, node) {
return data.replace(/</?[^>]+(>|$)/g, "");
}
}
}

最新更新