how to convert the yaml to spreadsheet?

∥☆過路亽.° 提交于 2019-12-14 02:40:26

问题


how can i use ruby to convert a yaml file and keep on the indent format over cells to spreadsheet file.

the yaml file like this:

https://github.com/rails/rails/blob/v2.3.10/activesupport/lib/active_support/locale/en.yml


回答1:


You haven't clearly stated what you want this spreadsheet to look like so I can't be specific but you can use the YAML library to read the file into a data structure, then convert the data structure into one like a table (array of arrays of strings) then use the CSV library to output it to a file.

require 'yaml'
require 'csv'

yaml_txt = File.read 'input.yaml'
yaml_data = YAML.load yaml_txt

csv_table = [
    [1,'hello world', true], 
    ['a', 'b', 3.14159, 'c', 2, 3e8], 
    [nil, 'another row', 'bla']
]
#replace this^ with something that converts the yaml_data into a 2D array

File.open 'output.csv', 'w' do |f|
    f.puts( csv_table.map do |row|
        CSV.generate_line row
    end.join "\n" )
end

The current example will produce:

1,hello world,true
a,b,3.14159,c,2,300000000.0
,another row,bla

in output.csv.

You can then open the CSV spreadsheet with the following options:




回答2:


think, it's better to join rows with an empty string rather than "\n"



来源:https://stackoverflow.com/questions/4306173/how-to-convert-the-yaml-to-spreadsheet

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