New line in csv cell (rails) - ruby-on-rails

I'd like multiple pieces of data on different lines within the same CSV cell like this:
"String" 2-15-2021 05:26pm
"String ..."
"String..."
I have tried the following and ended up with \n in the cell and not an actual new line, like this "2-15-2021 05:26pm \nHi, it's ...".
["\n", time, text.body].join("\n")
[time, text.body, "\n"].join("\n")
[time, text.body].join("\n")
The input data is an array of hashes. The output of a row is a hash with keys and values, one of the values is a list of strings (or this can be a list of lists of string, I am playing with what I can get to work). The list of strings is where I am trying to add line breaks.
I am using this to create the csv:
CSV.open("data.csv", "wb") do |csv|
csv << list.first.keys
list.each do |hash|
csv << hash.values
end
end

I ended up needing a list of strings that I could then join and add new lines onto.
values = []
values.push("#{time}, #{text.body}")
# And then in the hash for the csv, setting the value for that column like this:
{ message: values.join("\n\n")}

Related

How to write data to excel file

I have a config table as below:
S.NO TableName SourceColumns
1 A a,b,c,d
2 B p,q,r,s,t,u
3 C m,n,o,p,q
4 D x,y,z
Here, result object consists of SourceColumns of each record from the table.
For instance, here it gets the 1 record values. Then I am writing those values to CSV(excel) file. This works.
CSV.open('C:\Actual\Test.csv', 'w') do |csv|
result.each do |eachrow|
csv << ["#{eachrow['a']}","#{eachrow['b']}","#{eachrow['c']}","#{eachrow['d']}"]
end
end
As, I have hardcoded my values in the above query, I am constructing the string per my SourceColumns and passing to query as below:
myformattedstring="#{eachrow['a']}","#{eachrow['b']}","#{eachrow['c']}","#{eachrow['d']}"
CSV.open('C:\Actual\Test.csv', 'w') do |csv|
result.each do |eachrow|
csv << [myformattedstring]
end
end
Now, the data is being treated as string. How, can i pass my string to the CSV so that I can write the actual values
If you want to insert only 1 column in your csv containing myformattedstring, you need to put the double quotes only at the beginning and the end of your string, and interpolate all the #{} inside those quotes, as opposed to repeating the quotes

Ruby - Output file in CSV comes in one column

I am trying to print my values in CSV file like following where data is array of hashes.
UPDATES:
CSV.open(fn, "wb") do |csv|
#first rows are always headers and the headers value is generated from the array of hashes
data.each do |name, values|
csv << [name, values.join(",")]
end
and values has data like : true,false,false,false and name is an array with data like: light.
But for some reason my columns are only 2 instead of 5. The values column is concatenated in one column.
How can I achieve multiple columns using above code ?
I think this should work:
CSV.open(fn, "wb") do |csv|
data.each do |name, values|
csv << [name, *values]
end
end
http://ruby-doc.org/core-2.0.0/doc/syntax/calling_methods_rdoc.html#label-Array+to+Arguments+Conversion

How to manipulate a CSV object in ruby?

I want to export some ActiveRecords in CSV format. After check some tutorials, I found this:
def export_as_csv(equipments)
attributes = %w[id title description category_id]
CSV.generate(headers: true) do |csv|
csv << attributes
equipments.each do |equipment|
csv << equipment.attributes.values_at(*attributes)
end
return csv
end
end
The problem is, I want to manipulate all in memory in my tests(i.e. I don't want to save the file in the disk). So, when I receive this csv object as return value, how I can iterate through rows and columns? I came from Python and so I tried:
csv = exporter.export_as_csv(equipments)
for row in csv:
foo(row)
But obviously didn't work. Also, the equipments are surely not nil.
CSV.generate returns string formatted according csv rules.
So the most obvious way is to parse it and iterate, like:
csv = exporter.expor_as_csv(equipments)
CSV.parse(csv).each do |line|
# line => ['a', 'b', 'c']
end
After some videos, I found that the return was the problem. Returning the CSV I was receiving a CSV object, and not the CSV itself.

Ruby on Rails Mongoid to csv

I would like to ask if any one know how correctly transfer Mongoid data in to CSV document?
I got a model Record and I want every row from Record to become row in CSV document. I got 90 columns (keys) in the Record and I want to exclude some of the them from CSV document but I do not wont manually type every key which I want to be on CSV document. My code is
#all_rows = Record.all
CSV.open(Rails.root.join('public', 'downloads', "file.csv"), "w") do |csv|
#allrows.all.each do |record|
csv << record
end
But it does not work I am getting error
undefined method `map' for #<Record:0x007f9cd9e242f8>
if i adding record.to_s
i am gating document full of records like this #<Record:0x007f801ba60d68>
If any one can please help me to fix it! Thank you!
You are using << method on csv (documentation), which expects to be called with array as an argument. That is why it tries to perform map method on your record.
Solution for your problem is adding array of attributes instead of record object. There is method attributes that will return hash with all attributes.
ignored_attributes = ["attribute_you_dont_want", "another_attribute"]
#all_rows = Record.all
CSV.open(Rails.root.join('public', 'downloads', "file.csv"), "w") do |csv|
#all_rows.each do |record|
csv << record.attributes.delete_if{ |attr, value| ignored_attributes.include?(attr) }.values
end
end
Note that I wrote #all_rows.each, you shouldn't call all method again.
This code will perform delete_if method on attributes hash and will remove any attributes with names included in ignored_attributes array. delete_if returns hash on which you can call values method to return only array of values.

CSV file formatting options during creation

I have the following code which contains data for the csv file.Now i want the data to be displayed aligned left for all the columns.
CSV.open("projects.csv",'w') do |row|
if user.god?
row << ["Project Name","Manager","Total Resources","Hours Required"]
each_project_detail.each do |project_detail|
row << [project_detail["project_name"], project_detail["manager_name"].join("\n"), project_detail["total_resources"], project_detail["estimated_hours"].round, project_detail["development_hours"].round, project_detail["extra_hours"].round]
end
else
row << ["Project Name","Hours Required","Hours Spent", "Extra Hours"]
each_project_detail.each do |project_detail|
row << [project_detail["project_name"], project_detail["estimated_hours"].round, project_detail["development_hours"].round, project_detail["extra_hours"].round]
end
end
end
CSV files cannot have formatting. There's no concept of alignment in columns. It's just comma separated values!

Resources