Trim 一个 excel 使用 PowerShell 的单元格

Trim a excel cell with PowerShell

是否可以 trim 像这样的 excel 单元格:

<newline>
<newline>
A
B
C
<newline>
<newline>

至:

A
B
C

我用 COM 对象试过了:

$excel = New-Object -ComObject Excel.Application
$wb = $excel.Workbooks.Open($path)
foreach ($ws in $wb.Worksheets){
[void]$ws.Cells.Trim()
}

但是 Trim() 不是一个有效的方法。对于完整的工作表或给定范围 ($ws.Range) 是否有任何其他方法 Trim excel 单元格?

Trim() is a method on System.String. You must use it on a cell's value, not the cell itself, and then update the changed value. I used UsedRange 但您可以将其更改为任何其他范围:

$excel = New-Object -ComObject Excel.Application
$wb = $excel.Workbooks.Open($path)
foreach ($ws in $wb.Worksheets){
    foreach ($cell in $ws.UsedRange) {
        if ($cell.Value2 -ne $null) {
            $cell.Value2 = $cell.Value2.Trim()
        }
    }
}

不要忘记 close 或之后清理 Excel 对象。