簡體   English   中英

比較2個Excel中的列,如果匹配,則將其他相應列的值從2個Excel復制到1個Excel

[英]Compare Column in 2 excel and If matches, copy the respective other column value from 2nd excel to 1st excel

我在下面的這些excel文件中必須比較“主機”,如果excel-1值與excel-2匹配,那么我必須在excel-1中創建一列,然后將“ HostGroup”從excel-2復制到excel- 1。

在“主機”的excel-1列中

在此處輸入圖片說明

和excel-2“ Host_Name”

在此處輸入圖片說明

e.g. excel-1 

Host

abc
def

excel-2

group     Host_name

grp1      plq
grp2      def
grp3      abc

Final output in excel-1

Group   host

grp3    abc
grp2    def

請需要一些方法

這應該工作:

Add-Type -AssemblyName Microsoft.Office.Interop.Excel

$excel               = New-Object -ComObject Excel.Application
$excel.Visible       = $false
$excel.DisplayAlerts = $false 

$wb1                 = $excel.Workbooks.Open( "C:\excel1.xlsx", [System.Type]::Missing, $false ) 
$wb2                 = $excel.Workbooks.Open( "C:\excel2.xlsx", [System.Type]::Missing, $true ) 

$ws1                 = $wb1.WorkSheets.item(1)
$ws2                 = $wb2.WorkSheets.item(1)

[void]$ws1.Range( 'A:A' ).EntireColumn.Copy()
$insertRange = $ws1.Range( 'A:A' ).EntireRow
[void]$ws1.Range( 'A:A' ).Insert( [Microsoft.Office.Interop.Excel.XlInsertShiftDirection]::xlShiftToRight )
[void]$ws1.Range( 'A:A' ).EntireColumn.ClearContents()
$ws1.Cells( 1, 1 ).Value2 = 'GROUP'

$searchRange = $ws1.Range( 'B:B' ).EntireColumn

$lineCounter = 2
while( $ws2.Cells( $lineCounter, 1 ).Value2 ) {

    $hostName     = $ws2.Cells( $lineCounter, 2 ).Value2.Trim('" ')
    $searchResult = $searchRange.Find( $hostName, [System.Type]::Missing, [System.Type]::Missing, [Microsoft.Office.Interop.Excel.XlLookAt]::xlWhole, [Microsoft.Office.Interop.Excel.XlSearchOrder]::xlByColumns )

    if( $searchResult ) {
        $group = $ws2.Cells( $lineCounter, 1 ).Value2
        $ws1.Cells( $searchResult.Row, $searchResult.Column - 1 ).Value2 = $group
    }
    $lineCounter++
}

[void]$wb2.Close()
[void]$wb1.SaveAs("C:\excel_new.xlsx")
[void]$wb1.Close()
[void]$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM