如何在Ruby on Rails中使用axlsx以自定义颜色设置货币格式?

时间:2019-03-08 11:47:04

标签: ruby-on-rails excel axlsx

我正在使用axlsx宝石来生成Excel工作表。

我使用以下代码在Excel中设置货币单元格的格式:

wb.styles.add_style(:format_code => '[Gray][A6A6A6]$#,##0_;[Red]($#,##0_)')

以上代码适用,但有一个缺点-negative currencies are rendered in redpositive currencies are NOT rendered in Gray。为什么会这样?

我还引用了此链接-https://support.office.com/en-us/article/Number-format-codes-5026BBD6-04BC-48CD-BF33-80F18B4EAE68

上面的链接具有此段:

To specify the color for a section in the format code, type the name of one of the following eight colors in the code and enclose the name in square brackets as shown. The color code must be the first item in the code section.
[Black] [Blue] [Cyan] [Green] [Magenta] [Red] [White] [Yellow] 
  1. 那么这是否意味着我只能使用上述一种颜色?
  2. 我可以使用十六进制代码来呈现自定义颜色-用十六进制代码A6A6A6表示浅灰色吗?

请帮助!

1 个答案:

答案 0 :(得分:1)

  
      
  1. 那么这是否意味着我只能使用上述一种颜色?
  2.   

如果您打算完全通过格式代码来执行此操作,则可以,因为这是唯一受支持的颜色转换,其他任何操作都会导致格式无效。 (通常被Excel称为“无法读取的内容”)

  

2。我可以使用十六进制代码来呈现自定义颜色-用十六进制代码A6A6A6表示浅灰色吗?

是的,因为您不需要在format_code中为正值指定颜色,而是只需在fg_color选项中指定默认颜色,就像这样

  wb.styles.add_style(fg_color: 'A6A6A6', format_code: '$#,##0.00_);[Red]($#,##0.00)')

现在,默认颜色为'A6A6A6',如果数字为负,则[红色]将覆盖默认颜色。

  

[暗示] 。3.如果我也想为零设置不同的颜色怎么办(链接页面的第3部分)

如果您需要其他功能,也可以像下面这样研究条件格式:

  zero_style = wb.styles.add(fg_color: 'FF69B4')  
  ws.add_conditional_formatting("A:A", # Indicates the cell range
      { type: :cellIs, 
        operator: :equal, 
        formula: "0", 
        dxfId:  zero_style, 
        priority: 1 
      })

现在:(假设以上所有条件)

  • 正值将为灰色(#A6A6A6)[默认]
  • 负值将为红色([Red]),格式为($#,## 0.00)[格式代码]
  • 确切为零的值将是Hot Pink(#FF69B4)[条件格式]