excel - 如何使用 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()
解决方案
这应该会有所帮助。请参阅代码中的注释以获取解释。
#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
文件之一:
推荐阅读
- spring-kafka - Spring Cloud Stream with Kafka Binder:/bindings Actuator API 不会停止生产者
- docker - 在 docker 容器中运行时 Nodemailer 连接超时
- amazon-s3 - 尝试在 AWS S3 上使用客户端 API 初始化 Datomic Cloud 时出现“无法读取密钥文件”错误
- java - 如何使用 JDBC 模板将 UUID 插入 RAW(16) 列?
- raspberry-pi - 每个树莓派都有自己唯一的 ID 号吗?
- spring - 第二步无法获取第一步插入的数据
- powershell - 如何使用 Powershell Compress-Archive 仅压缩文件夹中的 pdf?
- javascript - 无法连接到我的快速服务器中的 api 端点
- firebase - Flutter 错误:在 null 上调用了 getter 'iterator' - 我正在使用 FutureBuilder
- flutter - 是否可以有一个可以移动的按钮