2013-02-10 92 views
0

我想使用Rails和randym/axlsx將Excel文件保存到保存箱中。將Axlsx保存在保存箱中

我可以創建一個Axlsx :: Package對象,我甚至可以序列化它,所以在開發環境中將它保存到我的磁盤。

但我想使用futuresimple/dropbox-api將其上傳到保管箱。

它有多難?

def save_in_dropbox(project) 
    Dropbox::API::Config.app_key = ENV['DROPBOX_APP_KEY'] 
    Dropbox::API::Config.app_secret = ENV['DROPBOX_APP_SECRET'] 
    Dropbox::API::Config.mode = ENV['DROPBOX_ACCESS_TYPE'] 

    dropbox_client = Dropbox::API::Client.new(:token => ENV['DROPBOX_CLIENT_TOKEN'], :secret => ENV['DROPBOX_CLIENT_SECRET']) 
    logger.info "#{dropbox_client.account}" 

    # create Excel file 
    p = Axlsx::Package.new 
    p.workbook.add_worksheet(:name => "Basic Worksheet") do |sheet| 
     sheet.add_row ["First Column", "Second", "Third"] 
     sheet.add_row [1, 2, 3] 
    end 
    p.use_shared_strings = true 

    # Next line causes Error: undefined method `length' for true:TrueClass 
    # because p.serialize('file.xlsx')) is true 
    # but I don't want to save to my disk, on heroku I couldn't 
    # I want to save to my dropbox 
    dropbox_client.upload("#{ENV['DROPBOX_ROOT_PATH']}/file.xlsx", p.serialize('file.xlsx')) 

    #p.serialize('c:\file.xlsx') # that saves it to my development env disk :-(

    #uploaded_file = dropbox_client.upload "#{ENV['DROPBOX_ROOT_PATH']}/file.txt", "#{1.second.ago.to_s}\n\r#{project.title}" # Upload to Dropbox works fine 

    end 

回答

2

我建議你在這種情況下使用Package#to_stream。它會給你IO對象,然後你可以讀入上傳呼叫。

另一種方法是使用Package#serialize將其寫入磁盤,然後從文件系統讀取它。

我對dropbox_client並不熟悉,但如果它沒有正確處理IO流,我會感到驚訝。

最佳

-randym

+0

真棒! [to_stream](http://rubydoc.info/github/randym/axlsx/Axlsx/Package#to_stream-instance_method)工作原理:'dropbox_client.upload(「#{ENV ['DROPBOX_ROOT_PATH']}/file.xlsx」,p .to_stream()) '感謝您的幫助和這個偉大的寶石! – 2013-02-11 17:35:58