我正在尝试使用此命令通过 power shell 将 excel 文件导入为 csv 格式
import-excel c:\users\xxxx\TestFile.xlsx | export-csv c:\users\xxx\CSVFile.csv -NoTypeInformation -Encoding UTF8
它工作正常,但问题是当列值为空时,双引号不会出现。
样品输出:-
"98456","Millan, Don K","Millan","Don","K",,"MD","SPECIALISTS","UROLOGY",,,,"0-99",,
所需输出:-
"98456","Millan, Don K","Millan","Don","K","","MD","SPECIALISTS","UROLOGY","","","","0-99","",""
我的excel输入数据如下
那么在powershell中转换为csv时有什么方法可以获取所有空单元格的引号。
您的“缺失”值意味着属性是
$null
:
PS> [pscustomobject] @{
"col1" = "val1"
"col2" = $null
# ^^^^^ null value
"col3" = "val3"
} | convertto-csv
"col1","col2","col3"
"val1",,"val3"
# ^^ no content
如果您想在输出中使用空的带引号的字符串,则需要将该值放入数据中:
PS> [pscustomobject] @{
"col1" = "val1"
"col2" = ""
# ^^ empty string
"col3" = "val3"
} | convertto-csv
"col1","col2","col3"
"val1","","val3"
# ^^ empty string
因此,在使用
import-excel
导入数据后,迭代所有结果并将任何 $null
值更改为 ""
,然后再调用 export-csv:
$data = import-excel c:\users\xxxx\TestFile.xlsx
foreach( $item in $data }
{
foreach( $property in $item.psobject.properties )
{
if( $null -eq $property.Value ) { $property.Value = "" }
}
}
$data | export-csv c:\users\xxx\CSVFile.csv -NoTypeInformation -Encoding UTF8
如果您在更改属性值之前和之后显示属性值,结果可能不会看起来有任何不同,因为
$null
和""
都不会显示和可打印字符,但当您导出它们时,您将看到所需的输出。