Quantcast
Channel: AutoHotkey Community
Viewing all articles
Browse latest Browse all 579

Ask for Help (v2) • Re: Trying to Parse a CSV that has line breaks the way excel does it

$
0
0
@jsong55 it is unclear to me what you expect from your script. I also believe the premise might be wrong. When Excel exports to a CSV, cells that include a line break will show a linefeed (`n) while rows are delimited by a carriage return and a linefeed (`r`n). The image clarifies.
Because certain editors replace a single `n with `r`n, it is tricky to run your script the way you do. It is unclear whether there are single `n or if they have been replaced with `r`n. It is better to use fileread() as that will preserve the single `n's and not introduce unwanted "`r". That said parsing with the "CSV" option should still be the best way to deal with these files.
So, do you want to eliminate these single linefeeds i.e. "flatten" the cells that have multiple rows (=replace the `n with " ")? or do you want to preserve the linefeeds ?. Do you want to output to a string or to an array?
The code below will do both based on the csv file shown in the picture.

CODE:

csv := fileread("testcsv2.csv")

for x,y in strsplit(csv,"`r`n")
{
loop parse, y, "csv"
lst .= (a_index = 1 ? "":",") strreplace(a_loopfield,"`n"," ")
lst .= "`n"
}
msgbox trim(lst,"`n")

tbl := []
for x,y in strsplit(csv,"`r`n")
{
rw := []
loop parse, y, "csv"
rw.push(a_loopfield)
(y) && tbl.push(rw)
}
; show all cells
for x,y in tbl
for a,b in y
msgbox b " (cell " chr(64 + a) x ")"

20240331_132248.jpg
testcsv2.zip

Statistics: Posted by flyingDman — Today, 16:30



Viewing all articles
Browse latest Browse all 579

Trending Articles