问题
I implemented a CSV exporter which works like the following:
- User triggers CSV export
- App creates a new background job
- Job generates CSV using
CSV.generate
- Job saves file on Amazon S3 with paperclip (assign file with
StringIO
) - User can download CSV after job is done
This process works well!
Now I need to provide an xlsx export as well
I just tried to change the content type for the file to an xlsx format, but I got Content Spoofing errors with paperclip. I am also struggling to set the content type that it works on Windows and Mac machines. I researched a bit and found the following plugins:
- https://github.com/if1live/csv-xlsx-converter only a CLI
- https://github.com/scpike/excel2csv last commit 3 years ago
- https://github.com/zdavatz/spreadsheet Is that the way to go ? Commercial license costs ?
- https://github.com/weshatheleopard/rubyXL Anybody has running in production ?
- https://github.com/zenkay/simple-spreadsheet can only read files
- https://github.com/randym/axlsx Looks pretty good, but how to write into files ?
What I need:
- Way to convert CSV into XLSX OR Simple XLSX generator like
CSV.generate
- Generating file, which has correct content-types (LibreOffice, Microsoft Office, Numbers should be able to open the file without errors)
My current CSV generation
# data var filled up with with customers
CSV.generate(options) do |csv|
csv << [
'header 1',
'header 2'
]
data.each do |obj|
csv << [
obj.attr1,
obj.attr2,
]
end
end
file = StringIO.new(data) #mimic a real upload file
file.class.class_eval { attr_accessor :original_filename, :content_type } #add attr's that paperclip needs
file.original_filename = "customer-export.#{customer_export.params['format']}" #assign filename in way that paperclip likes
file.content_type = content_type # text/plain for CSV and ? for XLSX
# the file can be assigned to an paperclip attachment and this works for now perfect
BTW: Ruby 2.2, Rails 4.1
来源:https://stackoverflow.com/questions/49233416/best-way-to-convert-csv-file-into-xlsx-and-provide-both-formats-as-export-for-us