LoginSignup
7
3

More than 3 years have passed since last update.

rubyXL での印刷範囲の設定など

Last updated at Posted at 2019-08-15

はじめに

Rubyでどうしてもエクセルを扱わないといけない案件があったのでrubyXLを利用しました
https://github.com/weshatheleopard/rubyXL

個人的にいくつかハマったところをまとめます

セルの値を代入するchange_contentsがno method_errorになる

change_contentsの使い方としては以下で「test」という文字列がA1セルに代入されます

worksheet[0][0].change_contents('test')

これがno method errorで利用できない時、以下をrequireします

require 'rubyXL/convenience_methods/worksheet'

メモリを気にしない場合はこちら

require 'rubyXL/convenience_methods'

印刷範囲の設定

印刷範囲を設定したテンプレートに値を書き込み、値の量によって印刷範囲を動的に変更したい場合は以下のようにテンプレートのエクセルファイルの印刷設定を上書きします。

workbook.defined_names.each do |defined_name|
      defined_name.reference = "印刷!$A$1:$T$#{print_row}" if defined_name.reference.start_with?('印刷')
end

印刷範囲でタイトル行などを指定している場合

ただし、タイトル行などを指定していて印刷範囲がシートに複数ある場合は、上記の方法ではすべて上書きされます。

each内のdefined_nameの中身は以下のようになっており、nameがxlnm.Print_Titlesとなっている設定を上書きしないように、start_with?(xxx)の値をreferenceに合わせて調節します。

<RubyXL::DefinedName:0x000055919cacea08 @local_namespaces=[], @name="_xlnm.Print_Area", @comment=nil, @custom_menu=nil, @description=nil, @help=nil, @status_bar=nil, @local_sheet_id="1", @hidden=nil, @function=nil, @vb_procedure=nil, @xlm=nil, @function_group_id=nil, @shortcut_key=nil, @publish_to_server=nil, @workbook_parameter=nil, @reference="印刷!$A$1:$S$117">
<RubyXL::DefinedName:0x000055919cacb5d8 @local_namespaces=[], @name="_xlnm.Print_Titles", @comment=nil, @custom_menu=nil, @description=nil, @help=nil, @status_bar=nil, @local_sheet_id="1", @hidden=nil, @function=nil, @vb_procedure=nil, @xlm=nil, @function_group_id=nil, @shortcut_key=nil, @publish_to_server=nil, @workbook_parameter=nil, @reference="印刷!$1:$13">
7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3