Axlsx - 格式化单元格中的文本

时间:2015-11-24 14:33:17

标签: ruby-on-rails ruby axlsx

我似乎无法找到有关是否可以使用多个格式选项填充单个单元格的任何信息。

例如,我希望单元格A1填充文本: “ Hello 世界,这是 excel

这是否可行,如果可以,我会使用什么语法来执行此操作?

2 个答案:

答案 0 :(得分:6)

对于内联样式,请使用富文本。 Here is an example from the axlsx page:

  p = Axlsx::Package.new
  p.use_shared_strings = true
  wb = p.workbook
  wrap_text = wb.styles.add_style({:alignment => {:horizontal => :center, :vertical => :center, :wrap_text => true}}  )
  rt = Axlsx::RichText.new
  rt.add_run('I\'m bold, ', :b => true)
  rt.add_run('I\'m italic, ', :i => true)
  rt.add_run('I\'m strike' + "\n", :strike => true)
  rt.add_run('I\'m bold, italic and strike' + "\n", :b => true, :i => true, :strike => true)
  rt.add_run('I\'m style-less :D')
  wb.add_worksheet(:name => "RichText") do | sheet |
    sheet.add_row [rt], :style => wrap_text
  end
  p.serialize 'rich_text.xlsx'

如果您只想将多种样式应用于单元格,则需要使用差异样式。有两种选择:

首先,手动完成。基本上你说你的风格类型是:dxf。默认值为:xf。其他一切都是一样的。 From the docs on styles.rb:

p = Axlsx::Package.new
wb = p.workbook
ws = wb.add_worksheet

# define your styles
profitable = wb.styles.add_style(:bg_color => "FFFF0000",
                           :fg_color=>"#FF000000",
                           :type => :dxf)

ws.add_row ["Genreated At:", Time.now], :styles=>[nil, date_time]
ws.add_row ["Previous Year Quarterly Profits (JPY)"], :style=>title
ws.add_row ["Quarter", "Profit", "% of Total"], :style=>title
ws.add_row ["Q1", 4000, 40], :style=>[title, currency, percent]
ws.add_row ["Q2", 3000, 30], :style=>[title, currency, percent]
ws.add_row ["Q3", 1000, 10], :style=>[title, currency, percent]
ws.add_row ["Q4", 2000, 20], :style=>[title, currency, percent]

ws.add_conditional_formatting("A1:A7", { :type => :cellIs, :operator => :greaterThan, :formula => "2000", :dxfId => profitable, :priority => 1 })
f = File.open('example_differential_styling', 'w')
p.serialize(f)

其次,使用axlsx_styler gem。它使得应用多种样式变得非常容易。

答案 1 :(得分:0)

我假设你在谈论这个宝石?

https://github.com/randym/axlsx

看起来你不能:

https://github.com/randym/axlsx/issues/134

然而,这是一个旧线程,也许它已经实施了。在该页面的第一篇文章中尝试这种方法:海报抱怨它不起作用,但值得一试。

实际上,进一步向下阅读看起来有人添加了RichText格式选项,应该允许这样做。我不知道该如何做到这一点,请为它提供文档。