エクセルファイルでデータ出力する要件があって、リポジトリを眺めていて見つけたRubyXLを使ってみました。
こんなデータが入っているxlsx(OFFICE 2007以降)のA1を上書きするみたいなコードサンプルです。
report.xlsx
| A | B | C | D
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
1 | a-1 | b-1 | c-1 | d-1
2 | a-2 | b-2 | c-2 | d-2
class モデル名 < ActiveRecord::Base def self.to_xlsx file_base_uri = "/target/file/directory/path/" template_file = "report.xlsx" dl_file_name = "report_#{Time.now.to_i}.xlsx" Rails.logger.info "PARSING xlsx Start" # testing to load template xlsx tmp_workbook = RubyXL::Parser.parse(file_base_uri + template_file_name)[0].extract_data.each.with_index(0) { |r, index| Rails.logger.info r[0] Rails.logger.info r[1] Rails.logger.info r[2] Rails.logger.info r[3] } Rails.logger.info "PARSING xlsx End" # copy as download file FileUtils.cp(file_base_uri + template_file_name, file_base_uri + dl_file_name) Rails.logger.info "CREATING xlsx Start" new_workbook = RubyXL::Parser.parse(file_base_uri + dl_file_name) # overwrite cell new_workbook[0].add_cell(0, 0, "なにかの日本語") # save file new_workbook.write(dl_file_name) Rails.logger.info "CREATING xlsx End" return dl_filename end end
app/log/development.log PARSING xlsx Start a-1 b-1 c-1 d-1 a-2 b-2 c-2 d-2 PARSING xlsx End CREATING xlsx Start CREATING xlsx End Sent file report_1404875869.xlsx (0.1ms)
report_1404875869.xlsx
| A | B | C | D
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
1 | なにかの日本語 | b-1 | c-1 | d-1
2 | a-2 | b-2 | c-2 | d-2
今回の要件だとこの機能で充分でした。
なにかあったらrooとかaxlsxとか試してみるかもー。
-
- -
追記〜
蛇足かもしれないけど
each.with_index(0)
インデックスの最初の値を指定できるメソッドです。
0から始まる each_with_index もよく使いますが、
開始indexを指定できてブロックで使えるのです;;イイヨネ;;