Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

Import and Export CSV using PowerShell with all columns in double quotes

I am using below code to import and export to CSV. The reason why I am doing an export is because I need all columns in the exported CSV to be enclosed in double quotes. But with below code the double quote is only appearing at the first and last of every line.

Import-Csv c:Emp.csv | Export-Csv c:Emp1.csv -NoTypeInformation -Force

Please note that I have already tried below code (that works but takes longer time if size of CSV is > 200MB):

$inform = Get-Content C:A.csv 
$inform | % { 
  $info = $_.ToString().Replace("|", """|""") 
  $info += """" 
  $var = """" + $info 
  $var | Out-File D:B.csv -Append 
}

Sample input (CSV file):

1|A|Test|ABC,PQR

Sample output (CSV file):

"1"|"A"|"Test"|"ABC,PQR"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Export-Csv already adds double quotes around each field by itself, so all you need to do for that is instruct it to use the correct delimiter:

Import-Csv 'C:path	oinput.csv' -Delimiter '|' |
    Export-Csv 'C:path	ooutput.csv' -Delimiter '|' -NoType

However, Export-Csv adds quotes around all fields indiscriminately, so if you want to selectively add quotes around particular fields you're going to need a custom routine:

$reader = New-Object IO.StreamReader 'C:path	oinput.csv'
$writer = New-Object IO.StreamWriter 'C:path	ooutput.csv'

while ($reader.Peek() -ge 0) {
    $line = $reader.ReadLine().Split('|')
    for ($i=0; $i -lt $line.Count; $i++) {
        if ($line[$i] -like '*,*') {
            $line[$i] = '"{0}"' -f $line[$i]
        }
    }
    $writer.WriteLine(($line -join '|'))
}

$reader.Close(); $reader.Dispose()
$writer.Close(); $writer.Dispose()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...