# define the style for conditional formattingprofitable=book.styles.add_style(:fg_color=>"FF428751",:type=>:dxf)unprofitable=book.styles.add_style(:fg_color=>"FF0000",:type=>:dxf)
book.add_worksheet(:name=>"Color Scale")do|ws|ws.add_row["Previous Year Quarterly Profits (JPY)"]ws.add_row["Quarter","Profit","% of Total"]offset=3rows=20offset.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]endcolor_scale=Axlsx::ColorScale.newws.add_conditional_formatting("B3:B100",{:type=>:colorScale,:operator=>:greaterThan,:formula=>"100000",:dxfId=>profitable,:priority=>1,:color_scale=>color_scale})end
大于100000的单元格颜色越来越深,而小于的单元格越来越浅。
dataBar
dataBar格式化能够在单元格中同时显示数值和一个柱形图,非常直观漂亮。
123456789101112
book.add_worksheet(:name=>"Data Bar")do|ws|ws.add_row["Previous Year Quarterly Profits (JPY)"]ws.add_row["Quarter","Profit","% of Total"]offset=3rows=20offset.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]enddata_bar=Axlsx::DataBar.newws.add_conditional_formatting("B3:B100",{:type=>:dataBar,:dxfId=>profitable,:priority=>1,:data_bar=>data_bar})end
iconSet
iconSet方式是对于满足条件和不满足条件的单元格分别使用不同的图标。
123456789101112
book.add_worksheet(:name=>"Icon Set")do|ws|ws.add_row["Previous Year Quarterly Profits (JPY)"]ws.add_row["Quarter","Profit","% of Total"]offset=3rows=20offset.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]endicon_set=Axlsx::IconSet.newws.add_conditional_formatting("B3:B100",{:type=>:iconSet,:dxfId=>profitable,:priority=>1,:icon_set=>icon_set})end