Formatting a cell as Text using the axlsx spreadsheet ruby gem?

血红的双手。 提交于 2019-11-30 23:23:43

问题


I'm using the axlsx ruby gem to create Excel-compatible .xlsx files. I can't figure out how to override the cell type that is generated by it's automatic type detection. For Active Record model attributes of type string the gem is setting the Excel cell format to General, but I want it to use Text explicitly. That way I can avoid stripping leading zeros off of zip codes, etc.

Anybody know how to accomplish this?


回答1:


You can override the type of data using the types option on add row.

Something like:

worksheet.add_row ['0012342'], :types => [:string]

Grab me on irc (JST) if you need any help getting that to work.

Best

randym

edit --

I've added an example for this to examples/example.rb in the repo.

wb.add_worksheet(:name => "Override Data Type") do |sheet|
  sheet.add_row ['dont eat my zeros!', '0088'] , :types => [nil, :string]
end

https://github.com/randym/axlsx/blob/master/examples/example.rb#L349




回答2:


format_code: '@' will work for you. Please find below code for reference.

def default_data_type_as_string
    @xlsx_package = Axlsx::Package.new
    @workbook = @xlsx_package.workbook
    @worksheet = @workbook.add_worksheet(:name => "Introduction")
    default_style = @workbook.styles.add_style({ format_code: '@' })
    row_data_array = ['1', '2%', '3$']
    @worksheet.add_row row_data_array, :style => [nil, default_style, nil]
    @xlsx_package.serialize('default_data_type_as_string.xlsx')
end


来源:https://stackoverflow.com/questions/13594199/formatting-a-cell-as-text-using-the-axlsx-spreadsheet-ruby-gem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!