【问题标题】:Search & Replace in Excel without looping?在 Excel 中搜索和替换而不循环?
【发布时间】:2018-04-27 04:21:13
【问题描述】:

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

我的问题是,在一个只有 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

【问题讨论】:

  • 最终,PSExcel 可以替代您的 Excel Com 对象,并且可以让您的代码更加智能。
  • 目前除了在运行这段代码的环境中使用COM接口之外什么都做不了...

标签: excel powershell


【解决方案1】:
$Excel = New-Object -ComObject Excel.Application
$Workbook=$Excel.Workbooks.Open("Files\MyFile.xlsx”)
$WorkSheet = $Workbook.Sheets.Item(1)
$WorkSheet.Columns.Replace("ThisNeedsTobeReplaced","ImReplaced")

【讨论】:

  • 这太令人兴奋了!而且很简单。又优雅。迫不及待想试试这个!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 2013-05-19
  • 2014-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多