小编The*_*pro的帖子

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

我有这门课,我正在使用活动存储

class DataSheet < ApplicationRecord
  belongs_to :admin

  has_one_attached :excel_file
  after_save :create_user
end
Run Code Online (Sandbox Code Playgroud)

我知道有很多 gems 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
Run Code Online (Sandbox Code Playgroud)

现在我正在使用将 .xlsx 文件存储为二进制文件的主动存储。我无法找到将该文件作为 xlsx 文件读取的方法。虽然主动存储提供了下载方法来获取文件的二进制数据。

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 …
Run Code Online (Sandbox Code Playgroud)

excel blob ruby-on-rails rails-activestorage ruby-on-rails-5.2

5
推荐指数
1
解决办法
2070
查看次数