Skip to content

Instantly share code, notes, and snippets.

@MattPorto
Last active January 31, 2024 05:52
Show Gist options
  • Save MattPorto/7ecbd1153756a5396dbfc96948cb0e97 to your computer and use it in GitHub Desktop.
Save MattPorto/7ecbd1153756a5396dbfc96948cb0e97 to your computer and use it in GitHub Desktop.
# A code snippet that helps me to rescue Zip::Error when handling .xlsx files on Rails
@file = params.fetch(:file)
begin
# try to open xlsx with roo gem
@spreadsheet = Roo::Excelx.new(@file.path, file_warning: :ignore)
rescue Zip::Error # corrupted xlsx file
# if got zip error, try to save the content in csv before open it
filepath = "#{Rails.root}/tmp/tmp_spreadsheet.csv"
# don't forget to `.force_encoding("utf-8")` to fix content error (was essential in my context)
File.open(filepath, "w") { |file| file.puts @file.read.force_encoding("utf-8") }
@spreadsheet = Roo::CSV.new(filepath)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment