1

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

$folderpath = %tempPath%
$filetype ="*xls"

Add-Type -AssemblyName Microsoft.Office.Interop.Excel

$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
write-host $xlFixedFormat
$excel = New-Object -ComObject excel.application
$excel.visible = $true
Get-ChildItem -Path $folderpath -Include $filetype -recurse | 
ForEach-Object `
{
 $path = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
 
 "Converting $path"
 $workbook = $excel.workbooks.open($_.fullname)

 $path += ".xlsx"
 $workbook.saveas($path, $xlFixedFormat)
 $workbook.close()
 

}
$excel.Quit()
$excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()

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

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

2 回答 2

1

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

Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
$htFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlHtml

$Date = get-date -format R
$CurrentLocation = Get-Location
$CurrentDir = Get-location

$Timestamp = get-date -format d

$xlsx = [String] $CurrentLocation + "\MyNewExcelStuff-" + $Timestamp + ".xlsx"

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.add()
$sheet1 = $workbook.worksheets.Item(1)
$sheet1.name = "Stuff"

$Sheet1.Cells.Item(1,1) = "Reporting Stack Stuff"
$title = $Sheet1.Range("A1:K1")
$title.Select() 
$title.MergeCells = $true
$title.VerticalAlignment = -4108           # Centre (vertically) heading
$title.HorizontalAlignment = -4108         # Centre (horizontally) heading
$Title.Interior.ColorIndex = 0

$Excel.ActiveWorkbook.SaveAs($xlsx, $xlFixedFormat)
Start-Sleep -s 2
$Excel.Quit()
$Excel = $Null

于 2021-12-08T07:11:03.397 回答
0

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

于 2021-12-08T13:50:32.347 回答