首页 > 解决方案 > 如何使用 PowerShell 将 Excel 工作簿文件名复制到单元格中?

问题描述

使用 PowerShell,我想打开一个 Excel 工作簿,复制工作簿的名称,然后将该名称粘贴到该工作簿中一个工作表 (Jpl) 上的单元格 (G6) 中。保存并关闭。

$Files=Get-ChildItem -Path "D:\MyExcelfiles\GR-E"
$xl = new-object -c excel.application
$xl.visible=$False
$xl.displayalerts = $False

foreach($File in $Files){
 
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($file.fullname)
Write-Host $baseName
$wb1 = $xl.workbooks.open($file, $null, $true)
$worksheet = $wb1.sheets.item("Jpl")
$bookname = $wb1.Range("G6")
$bookname.PasteSpecial(-4163)
$wb1.Save()
$wb1.Close()
 
}
$xl.Quit()

标签: excelpowershell

解决方案


这应该会有所帮助。请参阅代码中的注释以获取解释。

#Added the -File switch since you only want files.
#also added a filter for only excel files
$Files=Get-ChildItem -Path "G:\Test\Excel" -File -Filter "*.xls?"

$xl = new-object -c excel.application
$xl.visible=$False
$xl.displayalerts = $False

foreach($File in $Files) {
 
  Write-Host $File.baseName

  #Open file using fully qualified Path
  $wb1 = $xl.workbooks.open($file.FullName)

  $worksheet = $wb1.sheets("Jpl")

  #Couldn't get Range method to work switched to Cells
  $Worksheet.Cells(6,"G") = $File.BaseName

  $wb1.Save()
  $wb1.Close()
 
}

$xl.Quit()

使用 2 个测试文件的控制台输出:

JPLTest-1
JPLTest-A

文件之一:

在此处输入图像描述


推荐阅读