ruby利用webrick服务器将excel内容发到浏览器中

1101阅读 0评论2011-02-19 lijianweiabcde
分类:

require 'rubygems'
require 'webrick'
require 'win32ole'
#实现读excel的类
class Excel
  attr:excel 
  attr:usecase
  def open(filename,sheetname)
    begin
    @excel = WIN32OLE.new('excel.application')
    @workbook=@excel.WorkBooks.open(filename)
    @usecase = @workbook.WorkSheets(sheetname)
    rescue  WIN32OLERuntimeError
      raise "#{$!.to_s}"    
    end
  end
  
  def show
    return @usecase.Range("A1:Z10")['value']
  end
  
  def close
    @workbook.close(true)
    @workbook = nil
    @excel.quit()
    @excel = nil
    GC.start
  end
end
  
  
#实现一个页面,继承abstractservlet 类
class WebForm < WEBrick::HTTPServlet::AbstractServlet
 
# 实现对对浏览器的GET方法   
  def do_GET(request, response)
    status, content_type, body = print_questions(request) 
    response.status = status
    response['Content-Type'] = content_type
    response.body = body
  end
 
  # Construct the return HTML page
  def print_questions(request)
    html   = "
"
    html += "Name:

";
    html += "Name:

";
  str = <<'EOT'  "

on three

"
abcdef
EOT
html +=str.to_s
    html += ""
    @@m = html
    return 200, "text/html", html
  end
end

#实现另一个个页面
class PersistAnswers < WEBrick::HTTPServlet::AbstractServlet
#实现POST方法
   def do_POST(request, response)
    status, content_type, body = save_answers(request)
    response.status = status
    response['Content-Type'] = content_type
    response.body = body
  end
 
  # Save POST request into a text file
  def save_answers(request)
  ex=Excel.new
  ex.open("c:/xx.txt.xls","sheet1")
  new = ex.show
  
  str = <<'EOT'
EOT
 
  new.each  { |neweach|
    neweach.delete(nil)  
    neweach << str;
  }
  str=new.join("
")
  puts str
  ex.close
    # Return OK (200), content-type: text/plain, and a plain-text "Saved! Thank you." notice
    return 200, "text/html", str
  end
end
if $0 == __FILE__ then
  server = WEBrick::HTTPServer.new(:Port => 8000)
  server.mount "/questions", WebForm
  server.mount "/save", PersistAnswers
  trap "INT" do server.shutdown end
  server.start
end
上一篇:ruby中调用C语言的方法
下一篇:ruby patron包的简介