Merge 2 CSV Files with Powershell using Import-Excel

泄露秘密 提交于 2021-02-11 07:01:58

问题


I have 2 CSV Files that contain different information. There is one column which is similar in both files. I want to merge the two files by checking the ID Column to get a new file with all information from both files. So it should be like this:

File A

Column 1 = ID
Column 2 = Text
Column 3 = other Text

File B

Column 1 = ID
Column 2 = some other text

I want to merge them now using powershell and "import-excel" module to get one new csv:

File C

Column 1 = ID
Column 2 = Text
Column 3 = other text
Column 4 = some other text

回答1:


There are a number of ways to relate 2 (or more) data sets, but probably the most common in PowerShell is to find a common & unique property and use hash tables to relate one to the other.

Assuming you have the ImportExcel module; Here's a simple example based on the somewhat limited information you gave:

I created:

FileA:
ID   Text1          Tex2
1    something1.1   something2.1
2    something2.1   something2.2

FileB:
ID   Text3
1    SoemthingElse
2    SomethingElse2
$FileA      = 'c:\temp\fileA.csv'
$FileB      = 'c:\temp\fileB.csv'
$MergeFile  = 'c:\temp\FileA_BMerged.xlsx'
$FileB_Hash = @{}

# Create a hash table from the data in FileB indexed on the ID column.
Import-Csv -Path $FileB |
ForEach-Object{ $FileB_Hash.Add( $_.ID, $_) }

# Now Import FileA via Import-Csv and correlate the data using the ID to tie the 
# 2 sets together.
#
# Notice the use of Select-Object with a calculated property.
Import-Csv -Path C:\temp\FileA.csv |
Select-Object *,@{Name = 'Text3'; Expression = { $FileB_Hash.($_.ID).Text3 } } |
Export-Excel -Path $MergeFile

Export-Excel is the last and least obscure part it's simply taking the objects created earlier in the pipeline steps and outputting them into an Excel sheet.

You do have to be sensitive to the field names. Make sure your keys are unique otherwise you'll have to handle differently. The basic principal is when you encounter the ID in the first collection you can use it to easily reference the object in the second set then use that data to extend the data in the first.

We can mix this in different ways including not use either set as a basis and simply creating a collection of PSCustomObjects. However the main principal should be the similar.

Please give this a try and let me know how it goes.



来源:https://stackoverflow.com/questions/60657881/merge-2-csv-files-with-powershell-using-import-excel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!