我正在尝试使用powershell将Excel电子表格转换为CSV,下面是我正在使用的功能:
Function ConvertCSV{
Write-Host "Converting the list to CSV..."
$sExcelFile=$inputfile
$sCSVFile="C:\Users\%username%\Desktop\CACL.csv"
#Get COM Object
$oExcel = New-Object -ComObject "Excel.Application"
#Should Excel be visible?
$oExcel.Visible = $true
#and open excel file
$oExcelDoc = $oExcel.Workbooks.Open($sExcelFile)
# Open 1st Worksheet
$oWorksheet = $oExcelDoc.Worksheets.item(1)
#Activate, show it
$oWorksheet.Activate()
$oExcelDoc.SaveAs($sCSVFile,[Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVWindows)
$oExcelDoc.Close($false)
Start-Sleep 1
# Cleanup COM
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($oWorksheet)|out-null
$oWorksheet=$null
Start-Sleep 1
#Cleanup COM
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($oExcelDoc)|out-null
$oExcelDoc=$null
#Close Excel
$oExcel.Quit()
Start-Sleep 1
#Cleanup COM
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($oExcel)|out-null
$oExcel=$null
[GC]::Collect()
[GC]::WaitForPendingFinalizers()
}
ConvertCSV
然而,当我运行它并加载电子表格时,它说它无法打开“CALC.csv”,因为它已被破坏。以下是powershell报告的错误。
使用“2”参数调用“SaveAs”的异常:“SaveAs方法的Workbook类失败”
在第17行:5:
$ oExcelDoc.SaveAs($ sCSVFile,[Microsoft.Office.Interop.Excel.XlFileFormat] :: x ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~ + CategoryInfo:NotSpecified:(:) [],MethodInvocationException
FullyQualifiedErrorId:ComMethodTargetInvocation
答案 0 :(得分:4)
我认为您的问题是PowerShell无法扩展%USERNAME%变量。 PowerShell使用不同的语法来访问环境变量。在您的情况下,请尝试更改以下路径:
$sCSVFile="C:\Users\%username%\Desktop\CACL.csv"
为:
$sCSVFile="$env:USERPROFILE\Desktop\CACL.csv"