问题似乎是 Excel,即使您指定了逗号作为字段分隔符,总是看
什么被设置为系统 ListSeparator.. 即使您指定 'Other' 和 'OtherChar' 参数来使用逗号,它仍然会失败并需要一个分号..
在设置为分号 ; 的荷兰机器上,即使我的 csv 文件使用逗号,并且我将以下参数设置为 Comma,Excel 也会“翻译”为 [cultureinfo]::CurrentCulture.TextInfo.ListSeparator 中设置的内容
对我来说,当我在输入 CSV 文件中使用分号字符作为分隔符时,这会起作用,所以我需要先更改 csv 的格式:
$Delimiter = [cultureinfo]::CurrentCulture.TextInfo.ListSeparator
$file = 'D:Testcomma.csv' # the original comma delimited csv
(Import-Csv -Path $file) | Export-Csv -Path $file -Delimiter $Delimiter -NoTypeInformation
下一个问题是方法OpenText()似乎没有返回任何东西,解释错误信息You cannot call a method on a null-valued expression
# define an array of two-element arrays, in which the first element is the column number (1-based),
# and the second element is one of the XlColumnDataType constants specifying how the column is parsed.
# see: https://learn.microsoft.com/en-us/office/vba/api/excel.xlcolumndatatype
$FieldInfo = @(1, 1), @(2, 1), @(3, 1), @(4, 1), @(5, 1), @(6, 1), @(7, 1), @(8, 1), @(9, 1), @(10, 2), @(11, 1)
$Excel = New-Object -ComObject Excel.application
$Excel.DisplayAlerts = $false
$Excel.Visible = $true
# there are many parameters to the OpenText() method, but as we cannot use these as Named parameters
# we will have to provide all up to and including the FieldInfo parameter.
# note that for any variant parameter you wish to omit, we use [type]::Missing
$Excel.WorkBooks.OpenText($file, # The absolute full file path
2, # Origin: xlWindows
1, # StartRow (default 1)
1, # DataType: xlDelimited
1, # TextQualifier: xlTextQualifierDoubleQuote
[type]::Missing, # ConsecutiveDelimiter
[type]::Missing, # Tab ($true if the file is Tab delimited; default = $false)
[type]::Missing, # Semicolon ($true if the file is Semicolon delimited; default = $false)
[type]::Missing, # Comma ($true if the file is comma delimited; default = $false)
[type]::Missing, # Space ($true if the file is space delimited; default = $false)
$true, # Other ($true if the file delimited by the OtherChar; default = $false)
$Delimiter, # OtherChar (Required if Other is True; Specifies the delimiter character)
$FieldInfo)
# now get the workbook and worksheet in variables
$MyWorkbook = $Excel.WorkBooks.Item(1)
$MyWorkSheet = $MyWorkBook.WorkSheets.Item(1)