定義格式化操作
# define the style for conditional formatting
profitable = book.styles.add_style( :fg_color => "FF428751", :type => :dxf )
unprofitable = book.styles.add_style( :fg_color => "FF0000", :type => :dxf )
條件格式化有四種類型cellIs,colorScale,dataBar,iconSet。
cellIs
book.add_worksheet(:name => "Cell Is") do |ws|
# 產生20行數據
ws.add_row ["Previous Year Quarterly Profits (JPY)"]
ws.add_row ["Quarter", "Profit", "% of Total"]
offset = 3
rows = 20
offset.upto(rows + offset) do |i|
ws.add_row ["Q#{i}", 10000*((rows/2-i) * (rows/2-i)), "=100*B#{i}/SUM(B3:B#{rows+offset})"], :style=>[nil, money, percent]
end
# 格式化條件>100000
ws.add_conditional_formatting("B3:B100", { :type => :cellIs, :operator => :greaterThan, :formula => "100000", :dxfId => profitable, :priority => 1 })
# 格式化條件0.00%<x<100%
ws.add_conditional_formatting("C3:C100", { :type => :cellIs, :operator => :between, :formula => ["0.00%","100.00%"], :dxfId => unprofitable, :priority => 1 })
end
add_conditional_formatting方法指定條件格式化,類型type是cellIs,條件由operator和formula共同指定,dxfId就是我們上面定義的格式化操作,priority優先級數值越小,優先級越高。
colorScale
book.add_worksheet(:name => "Color Scale") do |ws|
ws.add_row ["Previous Year Quarterly Profits (JPY)"]
ws.add_row ["Quarter", "Profit", "% of Total"]
offset = 3
rows = 20
offset.upto(rows + offset) do |i|
ws.add_row ["Q#{i}", 10000*((rows/2-i) * (rows/2-i)), "=100*B#{i}/SUM(B3:B#{rows+offset})"], :style=>[nil, money, percent]
end
color_scale = Axlsx::ColorScale.new
ws.add_conditional_formatting("B3:B100", { :type => :colorScale, :operator => :greaterThan, :formula => "100000", :dxfId => profitable, :priority => 1, :color_scale => color_scale })
end
大於100000的單元格顏色越來越深,而小於的單元格越來越淺。
dataBar
book.add_worksheet(:name => "Data Bar") do |ws|
ws.add_row ["Previous Year Quarterly Profits (JPY)"]
ws.add_row ["Quarter", "Profit", "% of Total"]
offset = 3
rows = 20
offset.upto(rows + offset) do |i|
ws.add_row ["Q#{i}", 10000*((rows/2-i) * (rows/2-i)), "=100*B#{i}/SUM(B3:B#{rows+offset})"], :style=>[nil, money, percent]
end
data_bar = Axlsx::DataBar.new
ws.add_conditional_formatting("B3:B100", { :type => :dataBar, :dxfId => profitable, :priority => 1, :data_bar => data_bar })
end
iconSet
book.add_worksheet(:name => "Icon Set") do |ws|
ws.add_row ["Previous Year Quarterly Profits (JPY)"]
ws.add_row ["Quarter", "Profit", "% of Total"]
offset = 3
rows = 20
offset.upto(rows + offset) do |i|
ws.add_row ["Q#{i}", 10000*((rows/2-i) * (rows/2-i)), "=100*B#{i}/SUM(B3:B#{rows+offset})"], :style=>[nil, money, percent]
end
icon_set = Axlsx::IconSet.new
ws.add_conditional_formatting("B3:B100", { :type => :iconSet, :dxfId => profitable, :priority => 1, :icon_set => icon_set })
end