这里最大的挑战是您需要测试一个单元格是否包含某个日期值。
从您的图像中,您可以看到日期以不同的方式格式化,因此将单元格的值与特定格式的日期进行比较是很棘手的。
幸运的是,该DateTime
对象有一个静态方法FromOADate()
可以为您进行转换。
此外,您需要从下到上删除行,否则通过删除一行,下面的行的索引会更改,因为它们都向上移动一行。
$file = 'D:\Test\Export.xlsx'
# create a datetime variable to chack against
$checkDate = [datetime]::new(2099, 1, 1) # or do (Get-Date -Year 2099 -Month 1 -Day 1).Date
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
# open the Excel file
$workbook = $excel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item(1)
# get the number of rows in the sheet
$rowMax = $sheet.UsedRange.Rows.Count
# loop through the rows to test if the value in column 6 is date 01/01/2099
# do the loop BACKWARDS, otherwise the indices will change on every deletion.
for ($row = $rowMax; $row -ge 2; $row--) {
# convert the formatted date in the cell to real DateTime object with time values set all to 0
# Column 6 is the 'Valid until' column
$cellDate = [datetime]::FromOADate($sheet.Cells.Item($row, 6).Value2).Date
if ($cellDate -ne $checkDate) {
$null = $sheet.Rows($row).EntireRow.Delete()
}
}
# save and exit
$workbook.Close($true)
$excel.Quit()
# clean up the COM objects used
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
在上面的代码中,列索引被硬编码为 6 如果您不确定,但知道列名,您可以插入以下代码段:
# get the column index for column named 'Valid until'
$colMax = $sheet.UsedRange.Columns.Count
for ($col = 1; $col -le $colMax; $col++) {
if ($sheet.Cells.Item(1, $col).Value() -eq 'Valid until') { break } # assuming the first row has the headers
}
在线上方$rowMax = $sheet.UsedRange.Rows.Count
和循环内部$sheet.Cells.Item($row, 6).Value2
变为$sheet.Cells.Item($row, $col).Value2