diff --git a/README.md b/README.md index 639a2daa..039832dc 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,14 @@ sheet.to_xml sheet.to_yaml ``` +`#to_csv` acceptable for the parameters: + + # puts csv format content into a specified file + sheet.to_csv(filename: "/path/file.txt) + + # specify the custom separator for the content + sheet.to_csv(separator: ":") + ### Excel (xlsx and xlsm) Support Stream rows from an Excelx spreadsheet. diff --git a/lib/roo/formatters/csv.rb b/lib/roo/formatters/csv.rb index 3181f091..46afbc6c 100644 --- a/lib/roo/formatters/csv.rb +++ b/lib/roo/formatters/csv.rb @@ -1,7 +1,7 @@ module Roo module Formatters module CSV - def to_csv(filename = nil, separator = ",", sheet = default_sheet) + def to_csv(sheet = default_sheet, separator: ",", filename: nil) if filename File.open(filename, "w") do |file| write_csv_content(file, sheet, separator) diff --git a/spec/lib/roo/base_spec.rb b/spec/lib/roo/base_spec.rb index 76cefcc4..d8314784 100644 --- a/spec/lib/roo/base_spec.rb +++ b/spec/lib/roo/base_spec.rb @@ -268,8 +268,15 @@ def sheets expect(spreadsheet.to_csv).to eq(expected_csv) end + it 'should convert the spreadsheet to csv and put it into a file' do + file = Tempfile.new("test") + + expect(spreadsheet.to_csv(filename: file)).to be_truthy + expect(file.read).to eq(expected_csv) + end + it 'should convert the spreadsheet to csv using the separator when is passed on the parameter' do - expect(spreadsheet.to_csv(nil, ';')).to eq(expected_csv_with_semicolons) + expect(spreadsheet.to_csv(separator: ';')).to eq(expected_csv_with_semicolons) end end end