how can i use ruby to convert a yaml file and keep on the indent format over cells to spreadsheet 开发者_JAVA百科file.
the yaml file like this:
https://github.com/rails/rails/blob/v2.3.10/activesupport/lib/active_support/locale/en.yml
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:
think, it's better to join rows with an empty string rather than "\n"
精彩评论