使用 PowerShell 更新 Excel 中的多个连接字符串
Update multiple connection strings in Excel using PowerShell
我目前有一个 PS 脚本可以刷新具有 1 个数据连接的 Excel 文件,并且运行良好。问题是我已经构建了具有 3 个数据连接的其他 Excel 文件。当我尝试对具有 3 个数据连接字符串的文件使用以下代码时,数据得到处理,但只有一个数据连接得到更新。谁能告诉我需要做什么才能更新所有数据连接?我尝试重复代码的 "refresh all"/"Save" 部分,但这给了我错误消息。任何帮助将不胜感激。
$excel = new-object -comobject excel.application
$excel.DisplayAlerts = $false
$excelFiles = Get-ChildItem -Path "File Folder Location (ex. C:\Documents)" -Include *.xls, *.xlsm,*.xlsx, *.lnk -Recurse
Foreach($file in $excelFiles)
{
$workbook = $excel.workbooks.open($file.fullname)
$worksheet = $workbook.worksheets.item(1)
$workBook.RefreshAll()
$workbook.save()
$workbook.close()
}
$excel.quit()
根据您的关系,其中一种方法可能对您有所帮助(未经测试)
$excel = new-object -comobject excel.application
$excel.DisplayAlerts = $false
$excelFiles = Get-ChildItem -Path "$($env:userprofile)\Documents)" -Include *.xls, *.xlsm,*.xlsx, *.lnk -Recurse
Foreach($file in $excelFiles) {
$workbook = $excel.workbooks.open($file.fullname)
# ---- this method ----
foreach ($Conn in $workbook.Connections){
$Conn.OLEDBConnection.BackgroundQuery = $false
$Conn.refresh()
}
# ---- and/or this method ----
foreach ($Sheet in $workbook.Worksheets) {
foreach ($QTable in $Sheet.QueryTables) {
$QTable.BackgroundQuery = $false
}
}
# ----- might get you further, depneding on your connections ----
$workBook.RefreshAll()
$workbook.save()
$workbook.close()
}
$excel.quit()
我目前有一个 PS 脚本可以刷新具有 1 个数据连接的 Excel 文件,并且运行良好。问题是我已经构建了具有 3 个数据连接的其他 Excel 文件。当我尝试对具有 3 个数据连接字符串的文件使用以下代码时,数据得到处理,但只有一个数据连接得到更新。谁能告诉我需要做什么才能更新所有数据连接?我尝试重复代码的 "refresh all"/"Save" 部分,但这给了我错误消息。任何帮助将不胜感激。
$excel = new-object -comobject excel.application
$excel.DisplayAlerts = $false
$excelFiles = Get-ChildItem -Path "File Folder Location (ex. C:\Documents)" -Include *.xls, *.xlsm,*.xlsx, *.lnk -Recurse
Foreach($file in $excelFiles)
{
$workbook = $excel.workbooks.open($file.fullname)
$worksheet = $workbook.worksheets.item(1)
$workBook.RefreshAll()
$workbook.save()
$workbook.close()
}
$excel.quit()
根据您的关系,其中一种方法可能对您有所帮助(未经测试)
$excel = new-object -comobject excel.application
$excel.DisplayAlerts = $false
$excelFiles = Get-ChildItem -Path "$($env:userprofile)\Documents)" -Include *.xls, *.xlsm,*.xlsx, *.lnk -Recurse
Foreach($file in $excelFiles) {
$workbook = $excel.workbooks.open($file.fullname)
# ---- this method ----
foreach ($Conn in $workbook.Connections){
$Conn.OLEDBConnection.BackgroundQuery = $false
$Conn.refresh()
}
# ---- and/or this method ----
foreach ($Sheet in $workbook.Worksheets) {
foreach ($QTable in $Sheet.QueryTables) {
$QTable.BackgroundQuery = $false
}
}
# ----- might get you further, depneding on your connections ----
$workBook.RefreshAll()
$workbook.save()
$workbook.close()
}
$excel.quit()