在Excel中搜索和替换而不循环?

问题描述 投票:0回答:1

对于如何在excel文件列上进行批量搜索和替换,这似乎是the common answer on the internet

我的问题是,在一个只有8K行的文件中,在一个列中替换一个简单的双字符字符串需要5分钟,而文件的大小甚至不是1MB。

是否有更快/更好的方式,甚至是优化方法?

当前代码:(通过将搜索/替换逻辑放在单独的函数中,使其更加模块化和可重用)

function excel_search_replace ( $worksheet, $column_name, $search_str, $replace_str ) {
    echo "Replacing all '$search_str' with '$replace_str' in column '$column_name'"
    $range = $worksheet.Range( "$($column_name)1" ).EntireColumn
    $search = $range.find( $search_str )
    $i = 0

    if ( $search -ne $null ) {
        $i += 1
        $first_addr = $search.Address
        do {
            $i += 1
            $search.value() = $replace_str
            $search = $range.FindNext( $search )
        } while ( $search -ne $null -and $search.Address -ne $first_addr )
    }
    echo "...Found and replaced $i instances of '$search_str'"
    return $void
}

$source_file = 'C:\some\excel\file.xlsx'
$excel_obj = New-Object -ComObject 'Excel.Application'
$excel_obj.DisplayAlerts = $false
$excel_obj.Visible = $false
$workbook = $excel_obj.Workbooks.Open( $source_file ) # Open the file
$sheet = $workbook.Sheets.Item( 1 ) # select target worksheet by index

excel_search_replace $sheet 'A' 'find this' 'and replace with this'
[void]$workbook.save() # Save file
[void]$workbook.close() # Close file
[void]$excel_obj.quit() # Quit Excel
[Runtime.Interopservices.Marshal]::ReleaseComObject( $excel_obj ) >$null # Release COM
excel powershell
1个回答
4
投票
$Excel = New-Object -ComObject Excel.Application
$Workbook=$Excel.Workbooks.Open("Files\MyFile.xlsx”)
$WorkSheet = $Workbook.Sheets.Item(1)
$WorkSheet.Columns.Replace("ThisNeedsTobeReplaced","ImReplaced")
© www.soinside.com 2019 - 2024. All rights reserved.