简体   繁体   English

在excel中搜索多个项目并返回整个字段

[英]Search for multiple items in excel and return the entire feild

I have an excel file with multiple sheets which are populated with sku and quantity column.我有一个包含多张工作表的 excel 文件,其中填充了 sku 和数量列。 I need to search the entire workbook for multiple items and return their quantity.我需要在整个工作簿中搜索多个项目并返回它们的数量。 products.txt contains the sku IDs. products.txt 包含 sku ID。

ABC1234
BCDH214
LDJI983

And the Excel workbook, inventory.xlsx contains the following columns而 Excel 工作簿,inventory.xlsx 包含以下列

**sku**                  ***Quantity***
ABC1234                        2
BCDH214                        0     
LDJI983                        1 

I would like to run prodcuts.txt against inventory.xlsx and return the quantity of each product.我想针对inventory.xlsx 运行prodcuts.txt 并返回每个产品的数量。

Can this be done via powershell?这可以通过powershell完成吗? or any other way to run this kind of query?或任何其他方式来运行这种查询?

Use the code shown here Get Excel data without Excel and ensure you have the ACE.OLEDB provider installed.使用此处显示的代码在没有 Excel 的情况下获取 Excel 数据并确保您已安装ACE.OLEDB 提供程序。

I created a simple xlsx with:我创建了一个简单的 xlsx:

SKU    Quantity
one    1
two    4
three  9

Then I called into Excel:然后我打电话给Excel:

$path = 'd:\test\exceldb.xlsx'
$results = Get-ExcelData -Path $path -Query 'SELECT * FROM [Sheet1$]'

$stuffFromProductsTxtFile = 'one', 'two', 'three'

foreach ($sku in $stuffFromProductsTxtFile)
{
    $results.Rows | Where-Object {$_.SKU -eq $sku} | % {Write-Output "$($_.SKU) has quantity $($_.Quantity)"}
}

This gives the following output:这给出了以下输出:

one has quantity 1
two has quantity 4
three has quantity 9

I think with this, you can change accordingly to whatever you require.我认为有了这个,您可以根据需要进行相应更改。

For completeness , I have copied the sample code from the aforementioned MSDN blog here:为了完整起见,我已经从前面提到的 MSDN 博客中复制了示例代码:

function Get-ExcelData {
    [CmdletBinding(DefaultParameterSetName='Worksheet')]
    Param(
        [Parameter(Mandatory=$true, Position=0)]
        [String] $Path,

        [Parameter(Position=1, ParameterSetName='Worksheet')]
        [String] $WorksheetName = 'Sheet1',

        [Parameter(Position=1, ParameterSetName='Query')]
        [String] $Query = 'SELECT * FROM [Sheet1$]'
    )

    switch ($pscmdlet.ParameterSetName) {
        'Worksheet' {
            $Query = 'SELECT * FROM [{0}$]' -f $WorksheetName
            break
        }
        'Query' {
            # Make sure the query is in the correct syntax (e.g. 'SELECT * FROM [SheetName$]')
            $Pattern = '.*from\b\s*(?<Table>\w+).*'
            if($Query -match $Pattern) {
                $Query = $Query -replace $Matches.Table, ('[{0}$]' -f $Matches.Table)
            }
        }
    }

    # Create the scriptblock to run in a job
    $JobCode = {
        Param($Path, $Query)

        # Check if the file is XLS or XLSX 
        if ((Get-Item -Path $Path).Extension -eq 'xls') {
            $Provider = 'Microsoft.Jet.OLEDB.4.0'
            $ExtendedProperties = 'Excel 8.0;HDR=YES;IMEX=1'
        } else {
            $Provider = 'Microsoft.ACE.OLEDB.12.0'
            $ExtendedProperties = 'Excel 12.0;HDR=YES'
        }

        # Build the connection string and connection object
        $ConnectionString = 'Provider={0};Data Source={1};Extended Properties="{2}"' -f $Provider, $Path, $ExtendedProperties
        $Connection = New-Object System.Data.OleDb.OleDbConnection $ConnectionString

        try {
            # Open the connection to the file, and fill the datatable
            $Connection.Open()
            $Adapter = New-Object -TypeName System.Data.OleDb.OleDbDataAdapter $Query, $Connection
            $DataTable = New-Object System.Data.DataTable
            $Adapter.Fill($DataTable) | Out-Null
        }
        catch {
            # something went wrong :-(
            Write-Error $_.Exception.Message
        }
        finally {
            # Close the connection
            if ($Connection.State -eq 'Open') {
                $Connection.Close()
            }
        }

        # Return the results as an array
        return ,$DataTable
    }

    # Run the code in a 32bit job, since the provider is 32bit only
    $job = Start-Job $JobCode -RunAs32 -ArgumentList $Path, $Query
    $job | Wait-Job | Receive-Job
    Remove-Job $job
}

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

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