Last active
January 31, 2024 05:52
-
-
Save MattPorto/7ecbd1153756a5396dbfc96948cb0e97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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