简体   繁体   English

使用 PowerShell 修剪 Excel 单元格

[英]Trim a excel cell with PowerShell

Is it possible to trim a excel cell like this:是否可以像这样修剪excel单元格:

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

to:到:

A
B
C

I tried it with the COM Object:我用 COM 对象尝试过:

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

But Trim() is not a valid method.但是Trim()不是有效的方法。 Is there any other way to Trim excel cell(s) for a complete worksheet or a given range ($ws.Range) ?有没有其他方法可以为完整的工作表或给定的范围($ws.Range)修剪 excel 单元格?

Trim() is a method on System.String . Trim()System.String上的一个方法。 You must use it on a cell's value, not the cell itself, and then update the changed value.您必须在单元格的值上使用它,而不是单元格本身,然后更新更改后的值。 I used UsedRange but you can change it to any other range:我使用了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()
        }
    }
}

Don't forget to close or cleanup the Excel object after.之后不要忘记关闭或清理 Excel 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM