Powershell Excel SaveAs需要确认

pxy2qtax  于 2024-01-08  发布在  Shell
关注(0)|答案(3)|浏览(227)

我使用下面的脚本来转换一堆xls文件到xlsx。

  1. $folderpath = %tempPath%
  2. $filetype ="*xls"
  3. Add-Type -AssemblyName Microsoft.Office.Interop.Excel
  4. $xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
  5. write-host $xlFixedFormat
  6. $excel = New-Object -ComObject excel.application
  7. $excel.visible = $true
  8. Get-ChildItem -Path $folderpath -Include $filetype -recurse |
  9. ForEach-Object `
  10. {
  11. $path = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
  12. "Converting $path"
  13. $workbook = $excel.workbooks.open($_.fullname)
  14. $path += ".xlsx"
  15. $workbook.saveas($path, $xlFixedFormat)
  16. $workbook.close()
  17. }
  18. $excel.Quit()
  19. $excel = $null
  20. [gc]::collect()
  21. [gc]::WaitForPendingFinalizers()

字符串
它曾经完美地运行在VM上。不幸的是,随着更改文件夹路径,我意识到有弹出窗口来确认保存之前没有出现,脚本卡住了。任何简单的更正,可以防止该错误?

  1. "scriptError": {
  2. "localizedName": "Error",
  3. "value": "Unable to get the SaveAs property of the Workbook class\r\nAt C:\\Users\\~
  4. "variableName": "ScriptError"
  5. }

wfypjpf4

wfypjpf41#

下面是一个使用PowerShell保存Excel文件时如何设置路径的示例。我使用Get-Location小程序、Get-Date小程序和文件名的组合来设置路径,文件名存储在字符串变量中,供保存脚本时使用。

  1. Add-Type -AssemblyName Microsoft.Office.Interop.Excel
  2. $xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
  3. $htFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlHtml
  4. $Date = get-date -format R
  5. $CurrentLocation = Get-Location
  6. $CurrentDir = Get-location
  7. $Timestamp = get-date -format d
  8. $xlsx = [String] $CurrentLocation + "\MyNewExcelStuff-" + $Timestamp + ".xlsx"
  9. $excel = New-Object -ComObject Excel.Application
  10. $excel.Visible = $true
  11. $excel.DisplayAlerts = $False
  12. $workbook = $excel.Workbooks.add()
  13. $sheet1 = $workbook.worksheets.Item(1)
  14. $sheet1.name = "Stuff"
  15. $Sheet1.Cells.Item(1,1) = "Reporting Stack Stuff"
  16. $title = $Sheet1.Range("A1:K1")
  17. $title.Select()
  18. $title.MergeCells = $true
  19. $title.VerticalAlignment = -4108 # Centre (vertically) heading
  20. $title.HorizontalAlignment = -4108 # Centre (horizontally) heading
  21. $Title.Interior.ColorIndex = 0
  22. $Excel.ActiveWorkbook.SaveAs($xlsx, $xlFixedFormat)
  23. Start-Sleep -s 2
  24. $Excel.Quit()
  25. $Excel = $Null

字符串

展开查看全部
hmae6n7t

hmae6n7t2#

try $workbook.SaveCopyAs($path)
当我升级到Office 2016时,我在Azure DevOps管道中的Powershell脚本中出现了相同的错误消息。
升级后,它停止工作,但脚本仍然在同一升级的构建机器上手动工作正常。
1.最后我试着保存副本。
1.我还在代码中添加了以下行
$excel.visible = $false
$excel.DisplayAlerts=$false
1.我还创建了以下文件夹:

  • C:\Windows\SysWOW64\Windows\systemprofile\Desktop
  • C:\Windows\System32\Windows\Systemprofile\Desktop
syqv5f0l

syqv5f0l3#

你应该使用$workbook.Close($false)

相关问题