最近我有个需求要操作 导入/导出数据的操作,不知道 rails 操作 那种文件能方便些,查到有 parseexcel,FastCsv 的 gem 插件。希望高手指点!
用 CSV 导出中文真心有技巧啊!整了两个小时,值钱的就一句话,大家猜哪一句吧?
require 'csv'
class PartRequestsController < ApplicationController
def render_csv_header(filename = nil)
filename ||= params[:action]
filename += '.csv'
if request.env['HTTP_USER_AGENT'] =~ /msie/i
headers['Pragma'] = 'public'
headers["Content-type"] = "text/plain"
headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Expires'] = "0"
else
headers["Content-Type"] ||= 'text/csv'
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""
end
end
def index
@part_requests = PartRequest.where(:status => params[:status]).order('id DESC')
@status = params[:status]
respond_to do |format|
format.html # index.html.erb
format.json { render json: @part_requests }
format.csv do
render_csv_header 'Part_Request_Report'
csv_res = CSV.generate do |csv|
csv << PartRequest.new.attributes.keys
@part_requests.each do |o|
o.part_request_details.each do |d|
csv << o.attributes.values
end
end
end
send_data "\xEF\xBB\xBF"<<csv_res.force_encoding("ASCII-8BIT")
end
end
end
end
PS: mark down 处理这段代码也有 bug,今天真是个 bug 日啊!
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="Sheet1">
<Table>
<Row>
<Cell><Data ss:Type="String">导师姓名</Data></Cell>
<Cell><Data ss:Type="String">身份证号</Data></Cell>
...
<Cell><Data ss:Type="String">监护人手机</Data></Cell>
</Row>
<% @participants.each do |it| %>
<Row>
<Cell><Data ss:Type="String"><%= it.name%></Data></Cell>
<Cell><Data ss:Type="String"><%= it.id_number%></Data></Cell>
<Cell><Data ss:Type="String"><%= it.entry_code%></Data></Cell>
...
<Cell><Data ss:Type="String"><%= m1.mobile_number%></Data></Cell>
</Row>
<% end %>
</Table>
</Worksheet>
</Workbook>
直接用了 xml 方式导出 excel
这个是手写原始的 xml 格式吧,理论上都可以,但是不知道微软的 xml 怎么设置。
还有一些其它快捷的 xls 库,to_xls-rails 之类。
最近不碰 excel,具体不了解。