powershell - Powershell 写入 .XLSX 会损坏文件
问题描述
我有一个 Powershell 脚本,它循环遍历文件夹中的 .xslx 文件,密码用文件名保护它们(现在)。循环和写入 .xls 没有问题,但是当我尝试打开 .xlsx 文件后用 Powershell 编写它 - 我收到错误:
Excel 无法打开文件“abcd.xlsx”,因为文件格式或文件扩展名无效。验证文件没有损坏并且文件扩展名与文件格式匹配。
这是脚本:
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
$e = $ErrorActionPreference
$ErrorActionPreference="continue"
foreach ($f in Get-ChildItem "C:"){
try{
$ff = $f
$xlNormal = -4143
$s = [System.IO.Path]::GetFileNameWithoutExtension($f)
$xl = new-object -comobject excel.application
$xl.Visible = $False
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open($ff.FullName)
$wb.sheets(1).columns("A:S").entirecolumn.AutoFit()
$wb.sheets(1).columns("N").NumberFormat = "0.0%"
$a = $wb.SaveAs("C:\Out\" + $s + ".xls",$xlNormal,$s) #works
#$a = $wb.SaveAs("C:\Out\" + $s + ".xlsx",$xlNormal,$s) #doesn't work
$a = $xl.Quit()
$a = Release-Ref($ws)
$a = Release-Ref($wb)
$a = Release-Ref($xl)
}
catch {
Write-Output "Exception"
$ErrorActionPreference=$e;
}
}
我搜索了其他问题,但找不到从 Powershell 编写的相同问题的任何其他示例。谢谢你。
解决方案
使用 excel 有时使用 com 对象太复杂了。我推荐这个import-excel
模块。
Install-Module -Name ImportExcel
然后你可以做这样的事情。
function Release-Ref ($ref) {
$e = $ErrorActionPreference
$ErrorActionPreference="continue"
foreach ($f in Get-ChildItem $file){
try{
$filePass = gci $f
$path = split-path $f
$newFile = $path + "\" + $f.BaseName + "-protected.xlsx"
$f | Export-excel $newFile -password $filePass -NoNumberConversion * -AutoSize
}
catch {
Write-Output "Exception"
$ErrorActionPreference=$e;
}
}
}
推荐阅读
- python - 让 tensorflow 和 keras 在 GPU 上运行
- php - 如何从产品表和订单表中减去值?
- python - 如何在 Python 中检测 Ctrl+Key 而无需下载其他模块?
- python-3.6 - Discord Bot python 3.6 报告命令
- mysql - InnoDB:文件(未知):“读取”返回操作系统错误 403。无法继续操作;[错误] mysqld 出现异常 0x80000003 ;
- c# - 从文本文件中读取一行,然后用新文本 C# 替换同一行
- r - 有没有办法可以使用向量而不是这个 for 循环?
- c - 如何使用管道(两个孩子)在 fork 中打印两个 execl?
- python - 计划的 cron Python 脚本日志记录的工作方式与手动运行时不同
- java - 使用另一个文件中的类时,我不断收到一条错误消息,提示“找不到符号”