如何解决在 Excel 中使用 Powershell 检查列中的所有单元格值以触发每行的复制和粘贴
我有一个包含 2 个日期列的电子表格,每行只有一个日期值。有两列对于我来说是多余的,所以我想运行一个 powershell 脚本来检查 Date2 列中的每个单元格,如果为空,则将同一行上的 Date1 值复制到 Date2 列。那是我无法解决的部分;要检查 Date2 列中的所有单元格,如果为空,请复制相邻的 Date1 值。 完成后,我将删除 Date1 列。 注意:Date2 列具有更多日期,因此将其用作要保留的主要列(较少复制/粘贴)。 TIA
Example Test.xlsx:
A B
1 | Date1 | Date2 |
2 | 01/01/1900 | |
3 | 01/01/1900 | |
4 | | 01/01/1900 |
5 | | 01/01/1900 |
6 | 01/01/1900 | |
7 | | 01/01/1900 |
$Excel = New-Object -Com Excel.Application -Property @{Visible = $false} # Start Excel and hide the window
$Excel.displayAlerts = $False # disable comfirmation prompts
$Workbook = $Excel.Workbooks.Open(C:\Temp\Test.xlsx) # Open spreadsheet file
#This is the part I'm stuck on:
#If cell in column Date2 is empty,then copy the adjacent Date1 value to the Date2 cell - This is done until at the end of the columns
[void]$Workbook.Sheets.Item("Test").Cells.Item(1,1).EntireColumn.Delete() # Deleting "Date1" column
$Workbook.Save() # Save changes
$Workbook.Close($true) # Close workbook
$Excel.Quit() # Quit Excel
[Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) # Release COM
解决方法
您需要在代码中循环遍历行并更新第 2 (B) 列中的单元格(如果为空,则使用第 1 (A) 列的值)。
试试
$Excel = New-Object -Com Excel.Application -Property @{Visible = $false} # Start Excel and hide the window
$Excel.DisplayAlerts = $False # Disable comfirmation prompts
$Workbook = $Excel.Workbooks.Open("D:\Test\Test.xlsx") # Open spreadsheet file
$Sheet = $Workbook.Worksheets.Item("Test")
# get the total number of rows in the sheet
$rowCount = ($Sheet.UsedRange.Rows).Count
# update cell values in a loop
for ($row = 1; $row -le $rowCount; $row++) {
$value = $Sheet.Cells.Item($row,2).Text
if ([string]::IsNullOrWhiteSpace($value)) {
# copy the cell format first; then the value
$Sheet.Cells.Item($row,2).NumberFormat = $Sheet.Cells.Item($row,1).NumberFormat
$Sheet.Cells.Item($row,2) = $Sheet.Cells.Item($row,1)
}
}
[void]$Sheet.Cells.Item(1,1).EntireColumn.Delete() # Deleting "Date1" column
$Workbook.Save() # Save changes
$Workbook.Close($true) # Close workbook
$Excel.Quit() # Quit Excel
# clean up COM objects
$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()
,
这是一项重复性任务吗?如果没有,使用 excel 函数可能会更快。
无论如何,对于 excel 数据操作,我强烈建议使用 ImportExcel 模块
因此,您将读取包含两列作为属性的工作表,根据前两列的三元运算创建第三个属性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。