首页 > 解决方案 > 如何在 Rails 中加密 csv/xlsx 文件

问题描述

我想对我的 csv/xlsx 文件实施密码保护,但不知何故不能。我无法在互联网上找到写得很好的东西。我用 xlsx 试过这个。

render formats: :xlsx if current_user.save(validate: false)

在我的app/views/tools/export_database.xlsx.axlsx

wb = xlsx_package.workbook

wb.add_worksheet(name: "Users") do |sheet|
    sheet.sheet_protection.password = ENV['sheet_password']
    sheet.add_row %w(Id Email Role Verification First\ Name Last\ Name Title Birthday Postcode Telephone Payment Company\ Name Office\ Number Address Email\ Confirmed Agent\ Name Agent\ Position Agent\ Number Agent\ Email Company\ Logo Address\ Line\ 2 Town County Created\ At Updated\ At), :types => [:string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string]
    User.all.each do |user|
        sheet.add_row [user.id, user.email, user.role, user.verification, user.first_name, user.last_name, user.title, user.dob, user.postcode, user.telephone, user.payment, user.company_name, user.office_number, user.address, user.email_confirmed, user.agent_name, user.agent_position, user.agent_number, user.agent_email, user.company_logo, user.address_line_two, user.town, user.county, user.created_at, user.updated_at], :types => [:string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string]
    end
end

但这不起作用。

另一种实现是使用 CSV。

format.csv { send_data @users.to_csv, filename: "users-#{Date.today}.csv" }

在用户模型中。

CSV.generate(headers: true) do |csv|
      csv << attributes

      all.find_each do |user|
        csv << attributes.map{ |attr| user.send(attr) }
      end
    end

在此,我找不到如何添加密码。

还有另一种尝试的方法是使用prawnprawn-table但问题是,当列数增加时,表看起来不太好。请帮助我使用上述任何方法。感谢期待。

标签: ruby-on-railsrubycsvprawn

解决方案


虽然 Excel 文件支持密码保护,但 CSV 不支持。所以放弃 CSV 方法。

您用来生成 xlsx 的 gem 支持密码加密,这里有一个示例https://github.com/caxlsx/caxlsx/blob/282eec44ef01746ee25931fa6cd287ad083fd40b/examples/sheet_protection_example.md

当您说它不起作用时;它以什么方式不起作用?无法生成文件或者它生成了文件但它没有受到保护?


推荐阅读