簡體   English   中英

Powershell - 過濾 Excel 文件

[英]Powershell - Filter an Excel File

我想在 PowerShell 腳本中為 Excel 文件添加過濾器。

因此,“如果您在 D 列中找到條目“Listener”,則使整行不可見,因此將其過濾掉,以便只顯示沒有出現“Listener”的行。

我可以用 PowerShell 以某種方式實現這個嗎? 我試過了,但沒有用。

我用這個試過:

$column = 4 # column D
$filename = "C:\Users\xxxxx\Desktop\Test.XLS"
$criteria = "Listener"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$workbook = $Excel.Workbooks.Open($filename)
$worksheet = $workbook.Worksheets.Item(1)
$usedrange = $worksheet.UsedRange
$usedrange.EntireColumn.AutoFilter()
$usedrange.AutoFilter($column, $criteria)
$worksheet.UsedRange.offset($column,4).EntireLine.Delete()

謝謝

這應該適合你:

$column = 4 # column D
$filename = "C:\Users\xxxxx\Desktop\Test.XLS"
$criteria = "Listener"

$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$workbook  = $Excel.Workbooks.Open($filename)
$worksheet = $workbook.Worksheets.Item(1)
$worksheet.Activate()

# find the number of used rows in the table
$rowMax = $worksheet.UsedRange.Rows.Count
# hide rows that match the criteria
# go from bottom to top
# if your file does not have column headers, use $row -gt 0
for ($row = $rowMax; $row -gt 1; $row--) {
    if ($worksheet.Cells.Item($row, $column).Value() -eq $criteria) {
        $worksheet.Rows($row).Hidden = $true
    }
}

# save and close the workbook
$workbook.Close($true)

# quit Excel and clean up the COM objects from memory
$Excel.Quit()
# IMPORTANT: clean-up used Com objects
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

編輯

我可能誤解了您的問題,而不是像上面的代碼那樣隱藏符合條件的行,您只需要在“D”列上打開自動過濾器:

$column = 4 # column D
$filename = "C:\Users\xxxxx\Desktop\Test.XLS"
$criteria = "Listener"

$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$workbook  = $Excel.Workbooks.Open($filename)
$worksheet = $workbook.Worksheets.Item(1)
$worksheet.Activate()

# find the number of used rows in the table
$rowMax = $worksheet.UsedRange.Rows.Count
# add the autofilter to to column D
[void]$worksheet.Range("D$(1):D$($rowMax)").AutoFilter(1,"<>$criteria")

# save and close the workbook
$workbook.Close($true)

# quit Excel and clean up the COM objects from memory
$Excel.Quit()
# IMPORTANT: clean-up used Com objects
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM