0

我有一个每日下载的(使用 mechanize &when/sidekiq+redis).xls 文件,其中包含两个工作表,并希望将它们拆分为两个文件,每个文件都有一张。我尝试了很多方法都无济于事(以随机delete方法折腾,希望能奏效,不):

# goal: start with 1 file w/2 sheets and split into 2 files with 1 sheet each

def split_file
  open_xls = Spreadsheet.open 'my_file.xls'
  open_xls.write 'destination1.xls'
  open_xls.write 'destination2.xls'
  File.delete('my_file.xls')

  # open first new file and try to delete one sheet
  open_xls1 = Spreadsheet.open 'destination1.xls'
  sheet1 = open_xls1.worksheet(0)
  open_xls1.sheet1.delete   # from log: "NoMethodError: undefined method `delete'"
  open_xls1.write 'destination_only_sheet2.xls'

  # "" other sheet
  # repeat on 2nd file to remove other sheet

end

开始思考“电子表格 gem 是否像数组一样对待工作簿——我可以使用数组方法吗?”...然后举手。

主要的电子表格宝石资源:

4

1 回答 1

0

使用roowith roo-xlsgems(而不是spreadsheet单独使用)有效。我从 .xls 文件开始,无法改变这一事实。神奇的是 Roodefault_sheet和简单firstlast方法(因为 .xls 文件被转换为 .csv,它只接受保存单个工作表)。require 'spreadsheet'我在一个更广泛的 .rb 文件中有这个代码,我也有require 'csv'(不确定下面是否需要它们):

# in this example, there are only two sheets in the .xls file

class SomeClassName

  require 'roo'
  require 'roo-xls'

  def split_file

    # relative path to file
    file_path = File.join(Rails.root, "lib", "assets", "downloaded_file.xls")

    # retrieve original xls and save first sheet as .csv
    oldxls = Roo::Spreadsheet.open(file_path)
    oldxls.default_sheet = oldxls.sheets.first
    oldxls.to_csv("#{file_path}/new_file_name1.csv")

    # retrieve original xls and save second sheet as .csv
    oldxls = Roo::Spreadsheet.open(file_path)
    oldxls.default_sheet = oldxls.sheets.last
    oldxls.to_csv("#{file_path}/new_file_name2.csv")

    # delete original .xls
    File.delete("#{file_path}/downloaded_file.xls")

  end

end

SomeClassName.split_file
于 2016-01-23T15:07:25.453 回答