How to write data on multiple lines BUT within the same cell of csv?
To quote Wikipedia:
Fields with embedded line breaks must
be enclosed within double-quote
characters.
Like e.g.:
1997,Ford,E350,"Go get one now
they are going fast"
Retrieve multiple lines within same cell from CSV file
A CSV file may contain multi-line value in a cell. But it needs to be enclosed in quotes. Excel does this correctly - create a test file and save into CSV. PHP function fgetcsv also can read such files correctly.
Example file:
"col1","col2","col3"
"test1","test2.1
test2.2
test2.3","test3"
The second column in the second row contains multi-line value and this is a perfectly valid CSV file.
Here is the correct code:
$array_data = array();
$row = 0;
if (($handle = fopen("import/pdf_data.csv", "r")) !== FALSE) {
// read the CSV from root folder "web/interval/import"
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if ($row > 0) {
$array_data[$row] = $data;
}
$row++;
}
fclose($handle);
}
//loop through all the feature data array
foreach ($array_data as $row) {
list($col1,$col2,$col3) = $row;
echo "Name: ".$col1.", Surname: ".$col2.", Text: ".$col3."<br/>";
}
writing with python into a csv file with multiple lines in one cell
It looks like you need to send it an array of size 1 if you want your entries in a single row. You could pass ["joe"\n"john"\n"jane"]
with code like this:
writer.writerow(["\n".join(['joe','john','jane'])])
And for extra clarity:
In [2]: ["\n".join(['joe','john','jane'])]
Out[2]: ['joe\njohn\njane']
how to read a csv file that has multiple lines within the same cell?
I believe this should work. Also pandas can handle multiline text pretty well so try using also pd.read_csv().
import csv
file_path = 'yourfile.csv'
with open(file_path, newline='', encoding='utf-8') as f:
reader = csv.reader(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in reader:
print(row)
Adding a newline character within a cell (CSV)
This question was answered well at Can you encode CR/LF in into CSV files?.
Consider also reverse engineering multiple lines in Excel. To embed a newline in an Excel cell, press Alt+Enter. Then save the file as a .csv. You'll see that the double-quotes start on one line and each new line in the file is considered an embedded newline in the cell.
Inserting multiline text in a csv field
By default MS Excel uses semicolon as a separator. use ;
and you'll see this:
Exporting mutiline data into same cell in csv
To insert line breaks in csv
file you need to surround string with double quotes, so desired output is generated by following code :
public partial class Savestate
{
public static List<string> rtb1_list = new List<string>() { "hi1", "bye1" };
public static List<string> rtb2_list = new List<string>() { "hi2", "bye2" };
public static List<string> rtb3_list = new List<string>() { "hi3", "bye3" };
public static List<string> rtb4_list = new List<string>() { "hi4", "bye4" };
}
public static void Savetocsv()
{
Type s = typeof(Savestate);
FieldInfo[] fields = s.GetFields(BindingFlags.Public | BindingFlags.Static);
StringBuilder csvdata = new StringBuilder();
string header = String.Join(",", fields.Select(f => f.Name).ToArray());
csvdata.AppendLine(header);
string rtb1 = String.Join("\n", Savestate.rtb1_list.ToArray());
string rtb2 = String.Join("\n", Savestate.rtb2_list.ToArray());
string rtb3 = String.Join("\n", Savestate.rtb3_list.ToArray());
string rtb4 = String.Join("\n", Savestate.rtb4_list.ToArray());
string newlinestring = string.Format("\"{0}\",\" {1}\",\" {2}\",\" {3}\"", @rtb1, @rtb2, @rtb3, @rtb4);
csvdata.AppendLine(newlinestring);
string filepath = @"new.csv";
File.WriteAllText(filepath, csvdata.ToString());
}
Output file:
Related Topics
How to Generate Getters and Setters in Visual Studio
Error Reading Jobject from Jsonreader. Current Jsonreader Item Is Not an Object: Startarray. Path
Use Latest Version of Internet Explorer in the Webbrowser Control
How to Refresh an Entity Framework Core Dbcontext
Convert Date Format of String to Datetime Mm/Dd/Yyyy When System Date Formate Is Dd/Mm/Yyyy
How to Provide Success Messages ASP.NET MVC
Formatting Date in Linq-To-Entities Query Causes Exception
Add Client Certificate to .Net Core Httpclient
How to Convert a String Containing Am/Pm to Datetime
C# Multipart/Form-Data Submit Programmatically
Using Enum and | as Dictionary Key
How to Convert Json Date to .Net Datetime During Deserialization
How to Remove Windows Credentials
How to Show a Console Output/Window in a Forms Application
How to Change Cell Background Color in Wpf Datagrid
C# - How to Loop Through a Table to Update Each Row MySQL
How to Determine If .Net Core Is Installed
How to Create ASP.NET Identity Tables in an Already Created Database Using Code First