【问题标题】:Gem axlsx how to set font font_name?Gem axlsx如何设置字体font_name?
【发布时间】:2013-04-09 12:14:49
【问题描述】:

我使用 axlsx gem 来处理 xlsx 文件。 请帮我在工作表的单元格中设置字体。

item_style = s.add_style :b => false, :sz => 9,  :font_name => 'courier',
      :alignment => { :horizontal => :left, :vertical => :center, :wrap_text => true}
row = sheet.add_row [item.name, item.price], :style => item_style

但单元格中的字体仍然是“Arial”。 我需要任何“单宽”字体。 我知道 'courier' 不是单宽字体,仅以它为例。

因为我有固定的列宽。 我想知道单元格中的文本何时占用 2 行。 设置合适的行高。

谢谢。

【问题讨论】:

    标签: ruby axlsx


    【解决方案1】:

    看看你的风格声明,我觉得很合适。冒着听起来迂腐的风险,您应该将字体名称大写。

    结合你的观点和来自 acsmith 的好例子,下面的代码在 excel 中应该可以正常工作。您使用什么软件查看 Axlsx 文件?并非所有电子表格软件都完全/实现了 OOXML 规范。

    require 'axlsx'
    p = Axlsx::Package.new
    wb = p.workbook
    item_style = wb.styles.add_style :b => false, :sz => 9,  :font_name => 'Courier',
      :alignment => { :horizontal => :left, :vertical => :center, :wrap_text => true}
    wb.add_worksheet(:title => "Worksheet 1") do |sheet|
      sheet.add_row(["text in Courier"], :style => item_style)
    end
    p.serialize("courier.xlsx")
    

    最好的

    随意

    【讨论】:

    • 已解决。谢谢你。是的,你是对的。我使用 libreoffice 3.6.4.3,当我尝试在 Microsoft Excel 2007 中打开文件时,您和我的文件中的所有内容看起来都很好。之后我尝试安装 libreoffice 4.0.0.2。但这并没有帮助,所以 libreoffice 不支持此功能。幸运的是,我的客户使用 Excel。
    【解决方案2】:

    我建议尝试以下迷你示例并确保它有效。您需要将整个内容放在样式块中。

    p = Axlsx::Package.new
      wb = p.workbook
      wb.styles do |s|
        courier = s.add_style :font_name => "Courier"
        wb.add_worksheet(:title => "Worksheet 1") do |sheet|
          sheet.add_row(["text in Courier"], :style => courier)
        end
      end
    p.serialize("Courier.xlsx")
    

    我没有太多使用 axlsx,但我相信任何使用的样式都必须在样式块中声明,并在该块中使用。

    【讨论】:

    • 我复制并粘贴了您的代码,然后执行了它。字体仍然是“Arial”。但是感谢您的尝试。
    • acsmith 的好例子!仅供参考 - 块或内联声明很好。
    • 考虑@randym 下面的评论——当我只使用上面的代码生成文件时,Google Drive 会正确呈现文件。您可能想尝试在 Google Drive 中检查它,因为它可以解决您可能遇到的任何字体名称问题。
    【解决方案3】:

    由我们 Axlsx gem ,font_name 可以设置为这样多种方式,这对我有用:

    sheet.add_row ["some data", "","","", "", "","",""], :sz => 9,:height => 16,:font_name => "Arial"   -------------> first way
    
    sheet.rows.last.cells[0].font_name = "Arial"  ----------> second way
    
    sheet["A10"].font_name = "Arial"  -----------> third way
    

    对于多行:

    sheet["A1:E1"].each { |c| c.font_name = "Arial" } -------> fourth way
    
    @arial_fontfamily = s.add_style :b => 'true', :sz => 10,  :font_name =>   'Arial'  --> small css definition  -------> fifth way
    
    sheet["A1:E1"].each { |c| c.style = @arial_fontfamily  } -------> sixth way
    
    sheet.add_row ["some data", "","","", "", "","",""], :sz => 9,:height => 16,:style => @arial_fontfamily   -------------> seventh way
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 2014-06-21
      • 2016-09-30
      相关资源
      最近更新 更多