Best way to convert CSV file into XLSX and provide both formats as export for user

人走茶凉 提交于 2019-12-19 03:42:25

问题


I implemented a CSV exporter which works like the following:

  1. User triggers CSV export
  2. App creates a new background job
  3. Job generates CSV using CSV.generate
  4. Job saves file on Amazon S3 with paperclip (assign file with StringIO)
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!