Powershell将数据粘贴到现有工作表中

我有一个脚本,从现有的.csv文件中获取数据并将其复制到现有的工作簿(xlsx)中。

问题:它总是在工作簿中创build一个新工作表。

我想将数据添加到我目前的工作表,并开始在A5而不是顶部。 这是我的

 $source = 'C:\Scripts\monthly.csv' # source's fullpath $target = 'C:\Scripts\template.xlsx' # destination's fullpath $xl = new-object -com excel.application # creates Excel COM object in powershell $xl.displayAlerts = $false # don't prompt the user $wb2 = $xl.workbooks.open($source, $null, $true) # open source, readonly $wb1 = $xl.workbooks.open($target) # open target $sh1_wb1 = $wb1.sheets.item('triarqnew') # sheet in destination workbook $sheetToCopy = $wb2.sheets.item('monthly') # source sheet to copy $sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook $wb2.close($false) # close source workbook w/o saving $wb1.SaveAs("C:\scripts\Report.xlsx") # close and save destination workbook $xl.quit() 

Copy()PasteSpecial()那样尝试

 $source = 'C:\Scripts\monthly.csv' # source's fullpath $target = 'C:\Scripts\template.xlsx' # destination's fullpath $xl = new-object -com excel.application # creates Excel COM object in powershell $xl.displayAlerts = $false # don't prompt the user $wb2 = $xl.workbooks.open($source, $null, $true) # open source, readonly $wb1 = $xl.workbooks.open($target) # open target $sh1_wb1 = $wb1.sheets.item('triarqnew') # sheet in destination workbook $sheetToCopy = $wb2.sheets.item('monthly') # source sheet to copy # New code $sheetToCopy.UsedRange.Copy() $sh1_wb1.Range("A5").PasteSpecial() $wb2.close($false) # close source workbook w/o saving $wb1.SaveAs("C:\scripts\Report.xlsx") # close and save destination workbook $xl.quit()