繁体   English   中英

如何使用 Powershell 从 excel 中的一个工作簿的特定单元格复制信息并将其粘贴到另一个工作簿的特定单元格?

[英]How do I copy info from a specific cell from one workbook in excel and paste it to a specific cell to another workbook using Powershell?

所以基本上我想从一个单元格中提取信息,使用特定位置,复制该信息并将其粘贴到具有特定单元格位置的整个其他工作簿中,同时使用 Powershell。

这方面的一个例子是:从 wb1 (sheet4) 中的单元格 B2 复制 --> 粘贴到 wb2 (sheet3) 中的 A2

另外,我希望能够多次执行此操作(当然对于不同的单元格)

我尝试了下面的代码,这只是让我将整个工作簿提取到另一项工作中。 我知道可能有一种方法可以拉出特定的单元格,但我还不确定该怎么做。 有人可以帮忙吗?

$file1 = 'C:\Book1.xlsx' # <-- source file full path
$file2 = 'C:\Book2.xlsx' # <-- destination file full path
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item(1) # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('Sheet3') # source sheet to copy
$sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook
$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel

PS 有一个关于此的已回答问题,但代码使用 C#。 可以翻译成Powershell吗?

谢谢!

您可以通过以下方式获取/设置特定的单元格值:

# source/target cell
$sourceRange = $wb1.Worksheets.Item('Sheet4').Range('B2','B2')
$targetRange = $wb2.Worksheets.Item('Sheet3').Range('A2','A2')

# copy source value to target
$targetRange.Value = $sourceRange.Value

暂无
暂无

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

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