【问题标题】:Text after first comma following a double quoted string, is split across columns in csv in powershell在双引号字符串后的第一个逗号后的文本,在 powershell 中的 csv 列中拆分
【发布时间】:2014-02-18 18:11:39
【问题描述】:

我需要使用 powershell 将以下文本写入 csv 文件

这是一段文字,用来说明逗号​​和“双 引号”。因此,它非常重要

我正在使用流编写器及其 writeline() 来实现上述目的。但是,字符串“双引号”之后的第一个逗号之后的文本在输出文件中的两个单元格中被拆分。

我的输出是这样的:

单元格 1 的内容:这是一个文本,用于展示 逗号和“双引号”。因此

单元格2的内容:很重要

如何让整个输入文本只显示在一个单元格中?

这是我的代码 sn-p

    $id = '12345'
    $preamble = 'This is a text, to demonstrate the importance of comma and the "Double Quotes". Hence, it is very important'
    $filename = "Comma.csv"
    $currentDir = Get-Location
    $outputcsv = Join-Path $currentDir $filename
    $str = [System.IO.StreamWriter] $outputcsv
    $newrow = "$id,`"$preamble`""
    $str.WriteLine($newrow)
    $str.Close()

【问题讨论】:

    标签: powershell csv comma


    【解决方案1】:

    一般而言,当您创建文本中包含引号字符的 CSV 文件时,您需要使用两个引号字符。所以字符串

    This is a text, to demonstrate the importance of comma and the "Double Quotes". Hence, it is very important
    

    会像下面这样输入到 CSV 中

    "This is a text, to demonstrate the importance of comma and the ""Double Quotes"". Hence, it is very important"
    

    另一方面,由于您使用 PowerShell 创建 CSV 文件,因此您可能应该使用 Export-CSV cmdlet。

    【讨论】:

    • 谢谢 robert.westerlund :) 成功了!由于我的程序中的输入文本是从数据库中检索出来的,我所要做的就是用两个双引号替换一个双引号。
    • 您是否尝试过改用Export-Csv?我建议使用它而不是手动处理它。最终可能会为您省去很多麻烦。
    • 实际上,我的数据表中有一组行需要写入 csv 文件。我本可以直接使用 MyDataTable|Export-Csv,但我必须在每一行中添加一些硬编码的列值。因此我觉得 stream.writeline() 是一个更好的选择。此外,Export-csv 命令中的“-Append”开关会导致问题。
    • 不知道-Append 有什么问题,但是添加硬编码列应该不是问题。只需执行类似于MyDataTable | Select -Property *, @{N='AdditionalProperty'; E={'PropertyValue'}} | Export-Csv C:\myfile.csv -NoTypeInformation -Append 的操作
    猜你喜欢
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    相关资源
    最近更新 更多