繁体   English   中英

Powershell - 将.XLS文件转换为.XLSX

[英]Powershell - Convert .XLS file to .XLSX

我目前正在研究将 excel 文件从.xls 转换为.xlsx 的 powershell 脚本

准确地说,我需要它在某些方面起作用:

  1. 我需要文件夹中捕获 .xls 文件并将其复制到备份文件夹中

  2. 将它们转换为.xlsx 并将它们上传到上传文件夹

将它们从一个文件夹转换并将它们上传到另一个文件夹工作正常,但我尝试添加一些功能,现在我被卡住了。

这是我尝试运行时的错误:

At C:\Users\Test\Conv_XLS_V2.ps1:40 char:2
+ }
+  ~ The Try statement is missing its Catch or Finally block. At C:\Users\Test\Conv_XLS_V2.ps1:20 char:16
+ ForEach-Object { ~

      
Missing closing '}' in statement block or type definition.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingCatchOrFinally

我的代码:

# set folders
$downloadfolder = "C:\Users\Test"
#$downloadfolder = "folder that gets the .xls files"
$uploadfolder = "C:\Users\Test\Upload"
#$uploadfolder = "folder that uploads the .xlsx files"
$backupfolder = "C:\Users\Test\Backup"
#$backupfolder = "folder that has .xls files as backup"

#open and convert xls to xlsx
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
write-host $xlFixedFormat
$excel = New-Object -ComObject excel.application
$excel.visible = $true
$filetype ="*xls"
Get-ChildItem -Path $folderpath -Include $filetype -recurse | 
ForEach-Object {
    try {
        $xlsfilename = $_.fullname
        #copy file to backup folder
        Copy-Item  -Path $xlsfilename -Destination $backupfolder
        # open the xls
        Write-Output "Converting $xlsfilename"
        $workbook = $excel.workbooks.open($xlsfilename)
        # save converted file (as xlsx)
        $xlsxfilename = $xlsfilename + "x"
        $workbook.saveas($xlsxfilename, $xlFixedFormat)
        $workbook.close()
        #remove old file
        Write-Output "delete & move file(s)"
        Remove-Item -Path $xlsfilename -Force
        Move-Item -Path $xlsxfilename -Destination $uploadfolder -Force

    # garbage collection
    [gc]::collect()
    [gc]::WaitForPendingFinalizers()
}
# close excel
$excel.Quit()
$excel = $null

有人可以看看吗?

该错误描述了一个语法问题。 您已经包含了一个try {语句,但没有用} catch {}块关闭它。 就这样。

错误信息很清楚。 您忘记用结束括号}关闭try{..}块,并且try{..}后面应该跟随一个或多个catch{..}块,并且可以选择finally{..}块。
你可以阅读关于Try Catch Final的内容。

然后,还有其他一些错误和/或可以在您的代码中进行改进。

  • $folderpath未定义,应该是源文件夹$downloadfolder
  • 使用-Filter而不是-Include因为它更快。 你也遗漏了'*.xls'中的点
  • -File switch -File 到 Get-ChildItem cmdlet 以确保您不会收到并尝试处理目录
  • 可以将转换后的.xlsx文件直接保存到upload文件夹,无需先创建后移动
  • 要删除使用过的 COM 对象,请先从 memory 释放它们,然后启动垃圾收集。
    在您退出 Excel执行此操作。
# set folders
$downloadfolder = "C:\Users\Test"         # folder where the .xls files are
$uploadfolder   = "C:\Users\Test\Upload"  # folder that uploads the .xlsx files
$backupfolder   = "C:\Users\Test\Backup"  # folder that has .xls files as backup

# open and convert xls to xlsx
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false  # it is much faster if Excel is not visible

# loop through the .xls files and process them
Get-ChildItem -Path $downloadfolder -Filter '*.xls' -Recurse -File | 
ForEach-Object {
    try {
        $xlsfilename = $_.FullName
        #copy file to backup folder
        Copy-Item -Path $xlsfilename -Destination $backupfolder -Force
        # open the xls
        Write-Host "Converting $xlsfilename"
        $workbook = $excel.Workbooks.Open($xlsfilename)
        # save converted file (as xlsx) directly to the upload folder
        $newfilename = Join-Path -Path $uploadfolder -ChildPath ('{0}.xlsx' -f $_.BaseName)
        $workbook.SaveAs($newfilename, $xlFixedFormat)
        $workbook.Close()
        #remove old file
        Write-Host "Delete old file '$xlsfilename'"
        Remove-Item -Path $xlsfilename -Force
    }
    catch {
        # write out a warning as to why something went wrong
        Write-Warning "Could not convert '$xlsfilename':`r`n$($_.Exception.Message)"
    }
}
# close excel
$excel.Quit()
# garbage collection
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

非常感谢您的回答,对我帮助很大 <3

有一个很棒的一年!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM