ruby-on-rails - 如何在 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
在此,我找不到如何添加密码。
还有另一种尝试的方法是使用prawn和prawn-table但问题是,当列数增加时,表看起来不太好。请帮助我使用上述任何方法。感谢期待。
解决方案
虽然 Excel 文件支持密码保护,但 CSV 不支持。所以放弃 CSV 方法。
您用来生成 xlsx 的 gem 支持密码加密,这里有一个示例https://github.com/caxlsx/caxlsx/blob/282eec44ef01746ee25931fa6cd287ad083fd40b/examples/sheet_protection_example.md
当您说它不起作用时;它以什么方式不起作用?无法生成文件或者它生成了文件但它没有受到保护?
推荐阅读
- ruby-on-rails - Angular httpClient 发布请求发送重复的相同参数和空白值,为什么?
- mongodb - 猫鼬事务期间创建集合的正确方法
- azure - 创建 Azure 存储 Blob 容器时出现错误 403(已启用存储防火墙
- python - 如何使用 Python 在一个单元格中读取逗号分隔的字符串
- php - 显示来自 MySQL 的表,而无需对每个列名进行编码
- php - 如何使用 php 应用 MySQL 事务功能?
- julia - Julia 函数返回匿名函数
- python - 如何使用 python 从我自己的服务器发送电子邮件
- visual-studio-code - 是否可以更改 Visual Studio Code 默认资源管理器排序,使符号紧随其后?
- azure - Windows 虚拟桌面 (WVD) ARM 源 API 身份验证