rails 上载xls文件_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > rails 上载xls文件

rails 上载xls文件

 2011/12/22 9:21:34  itjavagoodqq  http://itjavagoodqq.iteye.com  我要评论(0)
  • 摘要:?<spanstyle="font-weight:normal;background-color:#fafafa;">以下两种form都可以上载文件(http://guides.rails.info/form_helpers.html#what-gets-uploaded)</span><h4><spanstyle="font-weight:normal;white-space:pre;background-color:#fafafa;"><
  • 标签:XLS 文件 rails

    ?<span style="font-weight: normal; background-color: #fafafa;">以下两种form都可以上载文件(http://guides.rails.info/form_helpers.html#what-gets-uploaded)</span>

<h4><span style="font-weight: normal; white-space: pre; background-color: #fafafa;"><span style="white-space: normal; background-color: #ffffff;">?</span>第一种</span></h4>
<div class="quote_title">
<%= form_tag({:action => :upload}, :multipart => true) do %>
  <%= file_field_tag 'picture' %>
<% end %>

<h4>第二种</h4>
<%= form_for @person do |f| %>
  <%= f.file_field :picture %>
<% end %>

?

controller中

?

def upload
  uploaded_io = params[:person][:picture]
  File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
    file.write(uploaded_io.read)
  end
end

?

?

实例:

涉及到xls读入并创建记录

view中

?

<%= form_for(@part, :url => {:action => "upload"}) do |f| %>
  <%= f.file_field :xls_file%>
  <%= f.submit %>
<% end %


?controller中


?

  def upload
    begin
      if params[:part][:xls_file]
        uploaded_io = params[:part][:xls_file]
        workbook = Spreadsheet.open(uploaded_io.tempfile)
        sheet = workbook.worksheet 0
        Part.transaction do
          sheet.each do |row|
            if row[0].is_a?(Float)
              part = Part.create!(:name=>row[1], :project_id => params[:part][:project_id], :size=>row[3], :material=>row[4], :quantity=>row[5].to_i, :weight=>row[6], :description=>row[8])
            end
          end
          redirect_to ......
        end
      else
        raise Errno::error #在没有选择导入文件直接点击上载时抛出一个异常
      end
    rescue => err
      logger.error(err)
      redirect_to ......
    end
  end

<address>
<span>?</span><span style="font-family: Arial, 'Liberation Sans', 'DejaVu Sans', sans-serif; font-size: 14px; line-height: 18px;">The Spreadsheet Library</span><span>:<span style="font-family: Arial, 'Liberation Sans', 'DejaVu Sans', sans-serif; font-size: 14px; line-height: 18px;"><a style="font-size: 14px; vertical-align: baseline; background-color: transparent; color: #0077cc; text-decoration: none; cursor: pointer; padding: 0px; margin: 0px;" rel="nofollow" href="http://spreadsheet.rubyforge.org/GUIDE_txt.html">http://spreadsheet.rubyforge.org/GUIDE_txt.html</a></span></span>
</address>
?

 
发表评论
用户名: 匿名