如何在PowerShell中实现多条件(城市+时效)删除Excel行?
需求说明
现有如下Excel表格数据:
| Street | City | Hour of Registration |
|---|---|---|
| hill st | bolton | 11/16/2022 10:00 |
| flo st | bolton | 11/15/2022 10:10 |
需求:当City字段值为bolton,且Hour of Registration距离当前时间≤24小时时,删除该行。以上述数据为例,仅第一行(hill st)需被删除。
现有问题
目前有一段PowerShell代码可实现单条件删除行,但不清楚如何实现多条件判断及时间计算逻辑。同时需注意:必须从下往上遍历行(从上往下会导致计数混乱,遗漏部分行)。
现有代码
$file = 'salehouses.xls' $excel = New-Object -ComObject Excel.Application $excel.Visible = $false # open file $workbook = $excel.Workbooks.Open($file) $sheet = $workbook.Worksheets.Item(1) # get max rows $rowMax = $sheet.UsedRange.Rows.Count for ($row = $rowMax; $row -ge 2; $row--) { $cell = $sheet.Cells[$row, 2].Value2 if ($cell -ieq 'bolton') { $null = $sheet.Rows($row).EntireRow.Delete() } $Filename = 'salehouses.xls' $workbook.SaveAs("c:\xls\salehouses.xls") $excel.Quit()
修改后的代码(实现多条件+时间判断)
$file = 'salehouses.xls' $excel = New-Object -ComObject Excel.Application $excel.Visible = $false $workbook = $excel.Workbooks.Open($file) $sheet = $workbook.Worksheets.Item(1) $rowMax = $sheet.UsedRange.Rows.Count $currentTime = Get-Date # 从下往上遍历行(避免删除行后计数混乱) for ($row = $rowMax; $row -ge 2; $row--) { $cityValue = $sheet.Cells[$row, 2].Value2 $registrationTime = $sheet.Cells[$row, 3].Value2 # 多条件判断:City是bolton,且注册时间距离当前时间≤24小时 if ($cityValue -ieq 'bolton' -and $registrationTime) { $timeDiff = ($currentTime - $registrationTime).TotalHours if ($timeDiff -le 24) { $null = $sheet.Rows($row).EntireRow.Delete() } } } $workbook.SaveAs("c:\xls\salehouses.xls") # 清理COM对象,避免进程残留 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null [GC]::Collect() [GC]::WaitForPendingFinalizers()
代码说明
$currentTime = Get-Date:获取当前系统时间$registrationTime = $sheet.Cells[$row, 3].Value2:获取第三列(Hour of Registration)的时间值,Excel的日期值可直接转换为PowerShell的DateTime对象($currentTime - $registrationTime).TotalHours:计算当前时间与注册时间的小时差- 多条件判断:先判断City是否为bolton,再判断时间差是否≤24小时,同时增加
$registrationTime非空判断,避免空值报错 - 增加COM对象清理代码:防止Excel进程在后台残留
测试数据集
截至2022年11月17日15:50,以下数据中所有注册时效≤24小时的行需被删除:
| Street | City | Hour Of Registeration | 时效 |
|---|---|---|---|
| hill st | Bolton | 11/16/2022 12:28 | >24hr |
| flow st | Bolton | 11/16/2022 13:39 | >24hr |
| jane st | Bolton | 11/16/2022 15:00 | >24hr |
| jack st | Bolton | 11/16/2022 15:00 | >24hr |
| Gone st | Bolton | 11/16/2022 18:16 | <24hr |
| top st | Bolton | 11/16/2022 18:27 | <24hr |
| sale st | Bolton | 11/16/2022 19:18 | <24hr |
| jack st | Bolton | 11/16/2022 20:14 | <24hr |
| Gone st | Bolton | 11/16/2022 20:28 | <24hr |
| top st | Bolton | 11/17/2022 02:51 | <24hr |
| sale st | Bolton | 11/17/2022 03:02 | <24hr |
| jack st | Bolton | 11/17/2022 06:21 | <24hr |
| Gone st | Bolton | 11/17/2022 08:51 | <24hr |
内容的提问来源于stack exchange,提问作者Nebelz Cheez
相关产品推荐
相关产品推荐

