Вики IT-KB

Пошаговые руководства, шпаргалки, полезные ссылки...

Инструменты пользователя

Инструменты сайта


apple-mac-os:macos-ventura:applescript-to-export-documents-from-apple-format-to-microsoft-excel-on-apple-macos

Скрипт AppleScript для экспорта документов из форматов Apple в форматы Microsoft Office в ОС Apple macOS

В этой заметке представлен пример скрипта AppleScript для экспорта документов из форматов Apple (pages, numbers, key) в форматы Microsoft Office (docx, xlsx, pptx) в ОС Apple macOS.


Выделяем один или несколько документов в формате pages, numbers и key, и выполняем скрипт. Если случайно будет выделен файл с другим расширением, обработка в скрипте пропустит такой файл.

--Orig https://www.macscripter.net/t/convert-pages-numbers-and-keys-to-ms-formats/74692
tell application "Finder"
 set SelectedItems to {}
 --Фильтр из выбранных файлов. Массив создаётся только из файлов с указанными расширениями
 repeat with FilteredItem in (get selection)
  if class of FilteredItem is document file and name extension of FilteredItem is in {"pages", "numbers", "key"} then ¬
   set end of SelectedItems to FilteredItem as alias
 end repeat
end tell
--Проходим по каждому файлу и запускаем обработчик в зависимости от расширения файла
repeat with SelectedItem in SelectedItems
 tell application "System Events"
  tell disk item (SelectedItem as text) to set {ItemName, ItemExtension} to {path, name extension}
  set ItemName to text 1 thru -((count ItemExtension) + 2) of ItemName
 end tell
 if ItemExtension is "pages" then
  my PagesExport(ItemName, SelectedItem)
 else if ItemExtension is "numbers" then
  my NumbersExport(ItemName, SelectedItem)
 else if ItemExtension is "key" then
  my KeyNoteExport(ItemName, SelectedItem)
 end if
end repeat
 
--Обработчики
--Проверка файла на существование перед экспортом
on AlertIfConvertedExist(thisItem)
 try
  alias thisItem
  set text item delimiters to ":"
  set FileName to text item -1 of thisItem as text
  tell application "Finder" to display dialog "Документ" & space & quoted form of FileName & space & ¬
   "был сконвертирован ранее." buttons {"Пропустить", "Заменить"} with icon caution
  if button returned of result is "Заменить" then return "toDelete"
  return "toSkip"
 end try
 return "toExport"
end AlertIfConvertedExist
 
--Проверка завершения экспорта
on CheckConvertedFile(thisItem)
 repeat
  try
   alias thisItem
   exit repeat
  end try
  delay 0.1
 end repeat
end CheckConvertedFile
 
--Экспорт pages -> docx
on PagesExport(ItemName, SelectedItem)
 set ConvertedItem to ItemName & ".docx"
 set aResult to my AlertIfConvertedExist(ConvertedItem)
 if aResult is "toSkip" then return
 if aResult is "toDelete" then tell application "System Events" to delete file ConvertedItem
 tell application "Pages"
  set toExport to open file SelectedItem
  export toExport to file ConvertedItem as Microsoft Word
  my CheckConvertedFile(ConvertedItem)
  close toExport saving no
 end tell
end PagesExport
 
--Экспорт numbers -> xlsx
on NumbersExport(ItemName, SelectedItem)
 set ConvertedItem to ItemName & ".xlsx"
 set aResult to my AlertIfConvertedExist(ConvertedItem)
 if aResult is "toSkip" then return
 if aResult is "toDelete" then tell application "System Events" to delete file ConvertedItem
 tell application "Numbers"
  set toExport to open file SelectedItem
  export toExport to file ConvertedItem as Microsoft Excel
  my CheckConvertedFile(ConvertedItem)
  close toExport saving no
 end tell
end NumbersExport
 
--Экспорт key -> pptx
on KeyNoteExport(ItemName, SelectedItem)
 set ConvertedItem to ItemName & ".pptx"
 set aResult to my AlertIfConvertedExist(ConvertedItem)
 if aResult is "toSkip" then return
 if aResult is "toDelete" then tell application "System Events" to delete file ConvertedItem
 tell application "Keynote"
  set toExport to open file SelectedItem
  export toExport to file ConvertedItem as Microsoft PowerPoint
  my CheckConvertedFile(ConvertedItem)
  close toExport saving no
 end tell
end KeyNoteExport

Если выбранный документ уже существует в формате docx/xlsx/pptx, то пользователь получает уведомление об этом и вариант на выбор: пропустить или заменить.

Для удобства использования можно создать быстрое действие в Команды.app и выполнять запуск из пункта «Быстрые действия» контекстного меню.

Перед использованием, в настройках Команды.app необходимо разрешить использование скриптов.

При первом запуске система несколько раз спросит о разрешениях запуска.


Проверено на следующих конфигурациях:

Версия ОС
Apple macOS Ventura (13.0)

Автор первичной редакции:
Виталий Якоб
Время публикации: 08.07.2023 11:05

Обсуждение

Ваш комментарий:
 
apple-mac-os/macos-ventura/applescript-to-export-documents-from-apple-format-to-microsoft-excel-on-apple-macos.txt · Последнее изменение: 08.07.2023 11:11 — Алексей Максимов

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki