Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-8 error when generating Excel file using axlsx gem

I am trying to use the axlsx gem to generate an Excel file. This is a Ruby Rails application where the user views a report in the browser and can click a link to export the data to Excel. However, I am getting the following error:

"ArgumentError (invalid byte sequence in UTF-8)."

This error is occurring on the following line of code:

p.to_stream.read.

I am using Ruby 1.9.3 and Rails 2.3.16. I am not serializing or trying to write the file to disk; I just want Excel to open the file and then the user can save the file if needed.

Has anyone ever seen this error?

like image 456
user2970270 Avatar asked Aug 01 '26 17:08

user2970270


1 Answers

I've seen the same error in a spec. I've yet to look into it further, but I forced the encoding to be binary for now:

# …

data = package.to_stream.read

data.force_encoding("BINARY")

expect(data).to be_present

I don't consider this a good solution, but I'm leaving it here as a workaround. I might update this answer if I keep digging.

EDIT: I've since tried doing the force_encoding in the code itself, so a generator class does to_stream.read.force_encoding("BINARY"). That seems to work: my UTF-8 strings look fine in LibreOffice in the created document.

like image 83
Henrik N Avatar answered Aug 04 '26 08:08

Henrik N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!