Here is the idea: I have a 2D array with non-escaped strings with newlines \n
and occasionally even characters that also act as CSV separators like ;
.
I need to easily be able to copy and paste such data from the output of a remote Ruby console into a local Excel file or an online Google spreadsheet.
It used to be working fine until I encountered data with newlines and semicolons using:
class Array
def puts_csv
map { |row| row.join(';') }.each(&method(:puts))
end
end
[["A1", "B1"], ["A2", "B2"], ["A3", "B3"]].puts_csv
# =>
A1;B1;
A2;B2;
A3;B3;
That outputs a list on the console that I could very easily copy/paste into my spreadsheet application and select ;
as the input delimiter.
But now I have to deal with string inputs containing characters that should be escaped, like commas, semicolons or newlines. This completely breaks my copy/pasting of data.
Sample data:
array2D = [
["name", "school", "comment"],
["Jean François", "ENS", "Lorem ipsum dolor sit amet; consectetur,\nadipiscing elit, sed do eiusmod tempor"
]
My current method gives three lines, because it breaks lines using a semicolon delimiter:
name;school;comment
Jean François;ENS;Lorem ipsum dolor sit amet;consectetur,
adipiscing elit, sed do eiusmod tempor
The target could be something like the following:
name;school;comment
Jean François;ENS;"Lorem ipsum dolor sit amet; consectetur,
adipiscing elit, sed do eiusmod tempor"
Thanks to "How to copy 2D array from console into a CSV/Excel file and properly handle newlines and separators" I realized there was a trick to deal with newlines by copying first to a Sublime Text file with escaped quotes and then opening it in Excel.
It is still difficult to copy such data directly into a spreadsheet because the newline is still considered a new row.
This code is generated from a remote server, whereas I am required to load the data in a local spreadsheet. It is for several reasons not convenient to exchange files via FTP or SMTP. This is only something that seldom happens so it's not worth adding code to the codebase to handle such exports, therefore I rely mostly on console patches to easily export some data.
For regular exports we have some code in place in other appslications.
How do I generate console output that I can easily paste into a spreadsheet?