如何使用活动存储读取.xlsx文件数据

时间:2018-05-28 01:48:24

标签: ruby-on-rails excel blob rails-activestorage ruby-on-rails-5.2

我有这个课,我正在使用主动存储

class DataSheet < ApplicationRecord
  belongs_to :admin

  has_one_attached :excel_file
  after_save :create_user
end

我知道有很多宝石creekwrite_xlsx_railsroo来读取或写入.xlsx文件,但它们都需要文件的物理位置。 以前,我使用creek gem来读取.xlsx文件,但我必须在本地保存该文件,如。

class LocalFileUploader


attr_reader :file

    def initialize(file = nil)
        @file = file
    end

    def save
        file_path = Rails.root.join('storage', file.original_filename)
        IO.copy_stream(file.path, file_path)
      return file_path.to_s
    end

end

现在我使用active storage将.xlsx文件存储为二进制文件。我无法找到将该文件作为xlsx文件读取的方法。虽然Active Storage提供了download方法来获取文件的二进制数据。

pry(#<DataSheet>)> self.excel_file
=> #<ActiveStorage::Attached::One:0x007f9db0607750
 @dependent=:purge_later,
 @name="excel_file",
 @record=#<DataSheet:0x007f9db811ba40 id: 3, admin_id: 1, created_at: Mon, 28 May 2018 01:33:06 UTC +00:00, updated_at: Mon, 28 May 2018 01:33:06 UTC +00:00>>

[3] pry(#<DataSheet>)> self.excel_file.blob
=> #<ActiveStorage::Blob:0x007f9db81125f8
 id: 6,
 key: "TBitz1dEzma2R2uTgtEoJ7X1",
 filename: "faizabad 1424.xlsx",
 content_type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
 metadata: {"identified"=>true},
 byte_size: 374211,
 checksum: "/shAXf0kEnYV4DGl0z3fng==",
 created_at: Mon, 28 May 2018 01:33:06 UTC +00:00>

[4] pry(#<DataSheet>)> SimpleXlsxReader.open self.excel_file.blob
TypeError: no implicit conversion of ActiveStorage::Blob into String
from /home/rotlu_crush/.rvm/gems/ruby-2.4.1/gems/rubyzip-1.2.1/lib/zip/file.rb:73:in `size?'
[5] pry(#<DataSheet>)> SimpleXlsxReader.open self.excel_file.blob.download
  Disk Storage (0.6ms) Downloaded file from key: TBitz1dEzma2R2uTgtEoJ7X1
ArgumentError: string contains null byte
from /home/rotlu_crush/.rvm/gems/ruby-2.4.1/gems/rubyzip-1.2.1/lib/zip/file.rb:73:in `size?'

我通过将二进制数据解析为csv来读取somwhere示例read csv file data with active storage

CSV.parse(materials_upload.csv_file.download, headers: true) do |row|
  # ...
end

有没有办法用活动存储读取excel文件?

2 个答案:

答案 0 :(得分:1)

Rails 6将添加ActiveStorage::Blob#open,将blob下载到tempfile:

data_sheet.excel_file.open do |file|
  # Operate on the file
end

您可以从GitHub捆绑Rails以使用此功能:

gem "rails", github: "rails/rails"

答案 1 :(得分:0)

您可以使用宝石xsv,然后致电

x = Xsv::Workbook.open(blob.download)

sheet = x.sheets[0]

# Iterate over rows
sheet.each_row do |row|
  row # => ["header1", "header2"], etc.
end