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
Related
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")}
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
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.
Currently, I'm using Rails and able to export, but there are values within the DB that are in a numeric format, and I need them to be translated into an alphanumeric format. I have the translations, but I don't know how to do it while exporting to CSV
Here's my current snippet of code to export to CSV
def self.to_csv(mycolumns)
CSV.generate() do |csv|
csv << mycolumns
all.each do |ccts|
csv << ccts.attributes.values_at(*mycolumns)
end
end
end
So my initial thought was that I could go into each ccts and edit them, but I don't know how to access the value within the hash and alter it. And it's only for a specific column. For instance, if this table was for fruits, and one of the column names was Name. If I wanted to change a value of 0041 into Apple, but only within the Name column, I'm just not sure how to accomplish this.
The csv export code is very compact, especially this line:
csv << ccts.attributes.values_at(*mycolumns)
That makes it difficult to think about how to change it.
First think how you would export your value if it was a single column. It may look something like:
if column_name == :name
lookup_fruit_name(ccts.name)
else
ccts[column_name]
end
Now you need all the values of a ccts inside an array, so it can be sent to csv:
values = mycolums.map do |column_name|
if column_name == :name
lookup_fruit_name(ccts.name)
else
ccts[column_name]
end
end
csv << values
Then just place this inside the inner loop of your original export method.
If you think more functional, you just write an instance method that gets your value and does a conversion depending on the column:
def csv_value_for(column_name)
if column_name == :name
lookup_fruit_name( self.name )
else
self[column_name]
end
end
Then you can use it like this:
csv << mycolumns.map{|col| ccts.csv_value_for(col) }
My CSV is exporting as :
"user_name,course_code,completion_date,completion_status,score"
621,BTB,2014/4/22,complete,100
But I want it like :
"user_name","course_code","completion_date","completion_status","score"
"621","BTB","2014/4/22","complete","100"
The code that generates my export is :
csv << ["user_name,course_code,completion_date,completion_status,score"]
#completes.each do |quiz|
csv << [member.id.to_s, apply_course_code(#section), quiz.updated_at.strftime('%Y/%-m/%-d'), 'complete', '100']
end
How can I generate quotes separated values in my CSV?
You can pass an option force_quotes: true to wrap every entry with quotes. But in your header you have to pass an array of separated strings like this:
CSV.generate(force_quotes: true) do |csv|
csv << %w(user_name course_code completion_date completion_status score)
#completes.each do |quiz|
csv << [member.id.to_s, apply_course_code(#section), quiz.updated_at.strftime('%Y/%-m/%-d'), 'complete', '100']
end
end