在Excel中search多个项目并返回整个表单

我有一个excel文件与多个工作表,填充sku和数量列。 我需要search整个工作簿中的多个项目并返回它们的数量。 products.txt包含sku ID。

ABC1234 BCDH214 LDJI983 

而Excel工作簿inventory.xlsx包含以下列

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

我想对inventory.xlsx运行prodcuts.txt并返回每个产品的数量。

这可以通过PowerShell来完成吗? 或者任何其他方式来运行这种查询?

使用此处显示的代码在没有Excel的情况下获取Excel数据,并确保安装了ACE.OLEDB提供程序。

我创build了一个简单的xlsx:

 SKU Quantity one 1 two 4 three 9 

然后我打电话给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)"} } 

这给出了以下输出:

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

我想这样做,你可以根据你的需要做出相应的改变。

为了完整起见 ,我从这里复制了上述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 (eg '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 }