我正在编写一个代码来过滤掉Excel表格的第二列(B),其中包含侧面指示符。我正在尝试过滤并仅显示指标= >
以及相应的A列数据。但是,每当我运行下面的代码时,我都会收到错误
无法获取Range类的Autofilter属性
在行:14 char:1
CSV文件格式
Name SideIndicator
asdf = >
asdf = >
trew = =
由于我对使用PowerShell的Excel自动化很陌生,所以我很想找到我错的地方。
代码:
$file1 = "C:\Users\achowdhury\Desktop\Comparedfile.csv" # source's fullpath
$xl = New-Object -c Excel.Application
$xl.DisplayAlerts = $false # don't prompt the user
$wb1 = $xl.Workbooks.Open($file1) # open target
$sh1 = $wb1.Sheets.Item('Comparedfile') # sheet in workbook
$sh1.Select()
$sh1.Range("B1").Select()
$xlFilterValues = 7 # found in MS documentation
$filterList = @("= >")
$rng = $sh1.Cells.Item(2).EntireColumn # selecting the entire column for filtering
$rng.Select | Out-Null
$xl.Selection.AutoFilter($sh1, $filterList, $xlFilterValues)
$wb1.Close($true) # close and save workbook
$xl.Quit()
答案 0 :(得分:0)
所以,如果我找到了你,你就得到了一个像这样的CSV文件:
"left","direction","right"
"asdf","= >","qwert"
"asdf","= >","qwert"
"qwert","< =","asdf"
"asdf","= >","qwert"
您只希望列direction
等于= >
的行。为此,您不需要Excel。
$file1 = "C:\Users\achowdhury\Desktop\Comparedfile.csv" # source's fullpath
$filtered = Import-Csv -Path $file1 | where {$_.direction -eq "= >"}
现在您在变量$filtered
中有这些行,您现在可以将其导出到另一个CSV文件中,如下所示:
$file2 = "C:\Users\achowdhury\Desktop\Filteredcomparedfile.csv"
$filtered | Export-Csv -Path $file2 -NoTypeInformation
或者,如果您只想输出第一列的值(在我的示例中名为left
和direction
列:
$filtered | % { $output = $_.left, $_.direction -join " "; Write-Output $output;}
KR 京特