Получение файла не обнаружено, и память не работает при запуске сценария Powershell через java для преобразования PPT, XLS в PPT
Я устал запускать скрипт powershell через Java-приложение.
Я утомляю две операции
1) Преобразование ppt в pdf.
- Powershell - получить ячейку (например, B32) после запуска поиска значения в документе Excel
- Пароль исчезает из ODBC Data Source Administrator
- SQL-запрос Powershell для Excel
- Как преобразовать общее значение в формат даты
- Скрипт Powershell для соответствия состояниям значений ячейки excel
2) Преобразование xls в pdf.
Конфигурации, которые я использую,
MS Office 2013 в Windows 2008
Скрипт для преобразования PPT в PDF выглядит следующим образом
#Convert Powerpoint formats to pdf Param( [string]$inputPath, [string]$outputPath ) Add-type -AssemblyName Office Add-type -AssemblyName Microsoft.Office.Interop.PowerPoint $ppFormatPDF = 32 $ppQualityStandard = 0 $pp = new-object -comobject powerpoint.application $ppt =$pp.presentations.open($inputPath) $ppt.SavecopyAs($outputPath, $ppFormatPDF) # 32 is for PDF $ppt.close() $pp.Quit() $pp = $null [gc]::collect() [gc]::WaitForPendingFinalizers()
При запуске этого скрипта я получаю память из связанного исключения
Executing command: powershell -NonInteractive -NoLogo -NoProfile -ExecutionPolicy UnRestricted -File D:\WEB-INF\classes\resource\pptToPdf.ps1 -inputPath D:\Temp\testPpt1.pptx -outputPath D:\ConvertedPdf1.pdf Command Successful: code=0, stderr=Exception calling "Open" with "1" argument(s): "Not enough storage is available to complete this operation. (Exception from HRESULT: 0x8007000E (E_OUTOFMEMORY))" At D:\WEB-INF\classes\resources\pptToPdf.ps1:15 char:1 + $ppt =$pp.presentations.open($inputPath) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation You cannot call a method on a null-valued expression. At D:\WEB-INF\classes\resources\pptToPdf.ps1:16 char:1 + $ppt.SavecopyAs($outputPath, $ppFormatPDF) # 32 is for PDF + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At D:\WEB-INF\classes\resources\pptToPdf.ps1:17 char:1 + $ppt.close() + ~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
Может ли кто-нибудь направить меня за то, что происходит не так?
Второй для XLS в PDF скрипт
#Convert Excel formats to pdf Param( [string]$inputPath, [string]$outputPath ) $xlQualityStandard = 0 # Microsoft.Office.Interop.Excel.XlFixedFormatQuality $xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type] #$excelFiles = Get-ChildItem -Path $folderpath -include *.xls, *.xlsx -recurse $wb= $inputPath; $objExcel = New-Object -ComObject excel.application $objExcel.visible = $false $ci = [System.Globalization.CultureInfo]'en-US' $workbook = $objExcel.workbooks.open($wb) $workbook.Saved = $true $Name = $outputPath $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $Name) $objExcel.Workbooks.close() $objExcel.Quit()
При запуске этого скрипта получение входного файла не найдено исключение
Executing command: powershell -NonInteractive -NoLogo -NoProfile -ExecutionPolicy UnRestricted -File D:\WEB-INF\classes\resources \xlsToPdf.ps1 -inputPath D:\testXls.xls -outputPath D:\ConvertedPdf2.pdf Command Successful: code=0, stderr=Exception calling "Open" with "1" argument(s): "Microsoft Excel cannot access the file 'D:\testXls.xls'. There are several possible reasons: The file name or path does not exist. The file is being used by another program. The workbook you are trying to save has the same name as a currently open workbook." At D:\WEB-INF\classes\resources\xlsToPdf.ps1:21 char:2 + $workbook = $objExcel.workbooks.open($wb) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation Property 'Saved' cannot be found on this object; make sure it exists and is settable. At D:\WEB-INF\classes\resources\xlsToPdf.ps1:22 char:2 + $workbook.Saved = $true + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At D:\WEB-INF\classes\resources\xlsToPdf.ps1:26 char:2 + $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $Name) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
Я запускаю все эти скрипты через Java-приложение. Код выглядит следующим образом
String command = "powershell -NonInteractive -NoLogo -NoProfile -ExecutionPolicy UnRestricted -File D:\\WEB-INF\\classes\\resources\xlsToPdf.ps1 -inputPath D:\\testXls.xls -outputPath D:\\ConvertedPdf2.pdf"; System.out.println(command); // Executing the command Process powerShellProcess = Runtime.getRuntime().exec(command); // Getting the results powerShellProcess.getOutputStream().close(); String line; System.out.println("Standard Output:"); BufferedReader stdout = new BufferedReader(new InputStreamReader( powerShellProcess.getInputStream())); while ((line = stdout.readLine()) != null) { System.out.println(line); } stdout.close(); System.out.println("Standard Error:"); BufferedReader stderr = new BufferedReader(new InputStreamReader( powerShellProcess.getErrorStream())); while ((line = stderr.readLine()) != null) { System.out.println(line); } stderr.close(); System.out.println("Done");
Команды оболочки питания следующие:
Для XLS в формате PDF,
powershell -NonInteractive -NoLogo -NoProfile -ExecutionPolicy UnRestricted -File D:\WEB-INF\classes\resources\xlsToPdf.ps1 -inputPath D:\testXls.xls -outputPath D:\ConvertedPdf2.pdf
Для PPT в PDF,
powershell -NonInteractive -NoLogo -NoProfile -ExecutionPolicy UnRestricted -File D:\WEB-INF\classes\resources\pptToPdf.ps1 -inputPath D:\Temp\testPpt1.pptx -outputPath D:\ConvertedPdf1.pdf
Я получаю эти проблемы, когда я устаю запускать свой сценарий через свое приложение. Мое приложение и кошка-кошка находятся на диске D. Когда они не работают, я создал автономный класс java и запускаю скрипты через этот класс, скрипты работают через этот класс. Я даже выполнил команды powershell через командную строку и подсказку powershell. Они работают. Поэтому нет проблем с Windows 2008 и MS Office 2013.
Я пропустил что-то в своем приложении. Может кто-нибудь мне направить. Есть ли какие-либо разрешения или что-то еще? Эта проблема беспокоит меня в течение длительного времени.
Заранее спасибо.
- Сортировка столбца Excel в порядке DESCENDING
- Пользовательская функция Power shell в скрипте
- Включить скрипт PowerShell в Excel
- Выполните вывод с использованием экспортированных данных Excel / CSV, если нулевые значения найдены в 'foreach'
- Возьмите выбор ячеек Excel, сохраните каждый в диапазоне до переменной и распечатайте текст сценарию
- Экспорт конкретных столбцов из Excel в .csv Powershell
- Как экспортировать результаты в электронную таблицу Excel и выделить их зеленым цветом после удаления файлов из списка csv в Powershell?
- powershell не может читать содержимое 2-мерного массива