我面临一个挑战,我需要每天在XLSX文档中将现有的工作表名更改为新的工作表名,而不是保存它。
我的剧本是这样的:
$xlspath = "C:\Users\roger\Test - Test\Daily_Files\Testfile.xlsx"
$xldoc = new-object -comobject Excel.application
$xldoc.DisplayAlerts = $false
$xldoc.Visible =$false
$workbook = $xldoc.Workbooks.Open($xlspath)
$worksheet = $workbook.worksheets.item(1)
$worksheet.name = "Headcount"
$workbook.Save = ($xlspath)
$workbook.Close()
$xldoc.Quit()我总是会收到这个错误--即使这样,文件也会保存,并且名称已经更改:
C:\CommonUserData\Roger\Test\Test.ps1:8 char:1 + $workbook.Save = "C:\Users\roger\Test - Test\Daily_Files\ .+~+ CategoryInfo : OperationStopped:(:) [],COMException + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException‘
有人知道如何解决这个问题吗?还是让这个脚本变得很简单?
发布于 2022-08-19 11:43:35
您甚至不需要.Save()或.SaveAs()方法。只需使用参数$true关闭工作簿
$xlspath = "C:\Users\roger\Test - Test\Daily_Files\Testfile.xlsx"
$xldoc = New-Object -ComObject Excel.application
$xldoc.DisplayAlerts = $false
$xldoc.Visible =$false
$workbook = $xldoc.Workbooks.Open($xlspath)
$worksheet = $workbook.worksheets.item(1)
$worksheet.Name = "Headcount"
$workbook.Close($true) # save the updated workbook
$xldoc.Quit()
# Important: remove references to the used COM objects when finished so they don't keep lingering in memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xldoc)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()https://stackoverflow.com/questions/73405229
复制相似问题