編者按::OP已放棄此問題並要求在https://stackoverflow.com/questions/38766898/saving-excel-worksheets-to-pdf-using-powershell處作出變更。將Excel工作表自動導出爲PDF
我一直在試圖實現下面的PowerShell腳本,但沒有任何運氣。有人可以幫忙嗎?
我知道這個腳本將爲每個Excel工作簿保存1個PDF文件,但是一旦我得到這個工作,我會看看導出每個Excel工作表來分離PDF文件。
ExportTo-ExcelPDF.ps1從http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/06/save-a-microsoft-excel-workbook-as-a-pdf-file-by-using-powershell.aspx
$path = "c:\fso"
$xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$excelFiles = Get-ChildItem -Path $path -include *.xls, *.xlsx -recurse
$objExcel = New-Object -ComObject excel.application
$objExcel.visible = $false
foreach($wb in $excelFiles)
{
$filepath = Join-Path -Path $path -ChildPath ($wb.BaseName + ".pdf")
$workbook = $objExcel.workbooks.open($wb.fullname, 3)
$workbook.Saved = $true
"saving $filepath"
$workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath)
$objExcel.Workbooks.close()
}
$objExcel.Quit()
錯誤消息:
The property 'Saved' cannot be found on this object. Verify that the
property exists and can be set.
At C:\ExportExcel.ps1:23 char:2
+ $workbook.Saved = $true
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
saving C:\ExportExcel.pdf
Method invocation failed because [System.__ComObject] does not contain a
method named 'ExportAsFixedFormat'.
At C:\ExportExcel.ps1:25 char:2
+ $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
You cannot call a method on a null-valued expression.
At C:\ExportExcel.ps1:26 char:2
+ $objExcel.Workbooks.close()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "Quit" with "0" argument(s): "Call was rejected by callee.
(Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))"
At C:\ExportExcel.ps1:28 char:1
+ $objExcel.Quit()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : COMException
的第一個錯誤看起來像'$ workbook'爲空,並打開文件失敗。第二個錯誤看起來像'$ workbook'不是工作簿對象,或者可能是[docs](https://msdn.microsoft.com/en-us/library/office/ff198122(v = office.14).aspx )說「*如果PDF加載項當前沒有安裝,將會發生錯誤。*」意味着會發生?第三個錯誤是'$ objExcel'顯然是'$ null'。錯誤的組合看起來很奇怪 - 它是否編寫任何PDF文件?你在運行什麼樣的環境? (軟件版本,你如何運行它)? – TessellatingHeckler
根本沒有創建PDF文件。在Server 2012 R2主機/ Powershell 4.0/Office 2016 Pro Plus上運行。 – Ash
@TessellatingHeckler第一個錯誤並不一定意味着'$ workbook'是'$ null' - 只要$'workbook'表示的任何對象都沒有'Saved'屬性(假設'Set-StrictMode -Version 2'或更高)。同樣,第二個錯誤只是表示該對象沒有方法'ExportAsFixedFormat' - 特定參數不起作用,所以PDF插件是否安裝並不重要(尚)。第三個錯誤絕對是_not_暗示'$ objExcel'是'$ null'。這些對象存在,但(有些)沒有預期的成員,還有其他問題。 – mklement0