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

How to read .xlsx file data with active storage

我有这个 class 并且我正在使用活动存储

class DataSheet < ApplicationRecord
  belongs_to :admin

  has_one_attached :excel_file
  after_save :create_user
end

我知道有很多 gem creek, write_xlsx_rails, roo 可以读取或写入 .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 which store .xlsx file as binary. I couldn't able to find a way to read that file as xlsx file. Although Active storage provides 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 之类的。

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

有什么方法可以使用活动存储读取 excel 文件吗?

Rails 6 将添加 ActiveStorage::Blob#open,它将 blob 下载到临时文件:

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

您可以捆绑 GitHub 中的 Rails 今天使用此功能:

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

您可以使用 gem xsv 然后调用

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

sheet = x.sheets[0]

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