我有这门课,我正在使用活动存储
class DataSheet < ApplicationRecord
belongs_to :admin
has_one_attached :excel_file
after_save :create_user
end
我知道有很多 gems 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
现在我正在使用将 .xlsx 文件存储为二进制文件的活动存储。我无法找到一种方法将该文件读取为 xlsx 文件。虽然 Active storage 提供了下载方法来获取文件的二进制数据。
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 文件数据。
CSV.parse(materials_upload.csv_file.download, headers: true) do |row|
# ...
end
有什么方法可以读取带有活动存储的 excel 文件?