실제 PowerPoint 파일을 위한 Python PPTX 라이브러리 선택

ZIP 도구로 .pptx 파일을 열면 슬라이드보다 훨씬 많은 것을 발견할 수 있습니다. 포함된 Excel 통합 문서로 뒷받침되는 차트, 다섯 개의 패키지 파트로 나뉜 SmartArt 다이어그램, 애니메이션 타이밍 XML, 전환 정의, 발표자 노트, 최신 주석, 포함된 동영상, 하이퍼링크 관계 등입니다. 모든 Python PPTX 라이브러리는 편집하려는 텍스트 상자뿐 아니라 이 모든 것을 어떻게 처리할지 결정해야 합니다.
대부분의 비교는 기능 목록에서 멈추고 체크박스가 없는 것은 저장 시 파괴된다고 암시합니다. 우리는 해당 객체를 포함한 12슬라이드 PowerPoint 파일을 각 라이브러리에 통과시켜 패키지, 객체, 픽셀 수준에서 측정하여 그 가정을 테스트했습니다.
결과는 두 가지 질문을 분리합니다. 보존: python-pptx는 건드릴 수 없는 것을 유지하므로 대규모 편집 작업에 신뢰할 수 있습니다. 기능: 프로젝트가 해당 객체를 생성하거나 조작해야 할 때 격차가 드러납니다. 이 문서는 먼저 증거를 제시한 다음 각 API가 도달하는 범위를 매핑합니다.
PowerPoint 파일은 보이는 슬라이드 그 이상입니다
테스트 파일은 손으로 조립한 것이 아니라 PowerPoint 자체에서 COM 자동화를 통해 생성했으므로 실제 프레젠테이션에서 볼 수 있는 다양한 객체를 갖춘 대표적인 테스트 픽스처를 제공합니다. 12개 슬라이드와 35개 도형 요소가 있습니다. 제목 슬라이드, 외부 하이퍼링크가 있는 본문 텍스트, 4×3 표, 포함된 .xlsx로 뒷받침되는 세로 막대형 차트, 이미지, 그룹화된 도형, SmartArt 다이어그램, Fade 전환이 있는 애니메이션 도형 2개, 발표자 노트, 최신 검토 주석, 포함된 동영상, 페이지 내부 이동 링크가 포함됩니다.
압축을 풀면 81개 패키지 파트와 약 100KB입니다. 대부분의 파트는 독자에게 보이지 않지만 프레젠테이션을 지탱합니다. 애니메이션 슬라이드의 타이밍 XML, 전환 XML, 다섯 개의 SmartArt 파트(데이터, 레이아웃, 빠른 스타일, 색, 그리기), 작성자 메타데이터가 있는 주석 파트, 동영상용 미디어 파일입니다.

이 점은 라이브러리 선택에 중요합니다. OOXML 형식에는 "안전 모드"가 없기 때문입니다. 라이브러리가 패키지를 열고 다시 작성하고 저장할 때 그 모든 파트가 범위에 들어갑니다. 질문은 결코 "텍스트 상자를 추가할 수 있는가"만이 아닙니다. "요청받지 않은 80개 파트에 무엇을 하는가"입니다.
Python이 기존 PPTX를 저장하면 어떻게 될까요?
python-pptx 1.0.2, power-pptx 2.15.0, Spire.Presentation for Python 11.8.1(평가판)로 파일을 열고 편집 없이 저장한 뒤 세 계층을 감사했습니다. ZIP 패키지 구조, PowerPoint 자체가 COM을 통해 보고하는 객체 모델, 동일한 PowerPoint 엔진이 1280×720으로 렌더링한 12개 슬라이드 전체의 픽셀 수준 차이입니다. Spire.Presentation은 E-iceblue 자체 제품이며, 이 테스트는 게시자가 직접 수행했습니다. 아래에는 Spire에 덜 유리한 결과를 포함해 원시 결과를 보고합니다.
| 측정 항목 | 원본 | python-pptx | power-pptx | Spire |
|---|---|---|---|---|
| 슬라이드 | 12 | 12 | 12 | 12 |
| 도형 | 35 † | 35 | 35 | 35 |
| 애니메이션 시퀀스 | 2 | 2 | 2 | 2 |
| 전환이 있는 슬라이드 | 1 | 1 | 1 | 1 |
| SmartArt 노드 | 5 | 5 | 5 | 5 |
| 주석 | 1 | 1 | 1 | 1 |
| 동영상 / 차트 / 표 / 노트 | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 |
| 끊어진 관계 참조 | 0 | 0 | 0 | 0 |
| 렌더링된 픽셀 차이 | — | 0.000% | 0.000% | 0.000% |
† 도형 요소는 슬라이드 XML에서 집계됩니다. 그중 두 개는 그룹 안에 있으므로 PowerPoint의 최상위 도형 수는 모든 파일에서 33입니다. 아래 수정 테스트는 텍스트 상자를 하나 추가했기 때문에 34로 보고합니다.
표보다 더 중요한 두 가지 세부 사항이 있습니다.
첫째, python-pptx와 power-pptx는 파트를 추가하거나 잃지 않았습니다. 재직렬화가 공백과 반복된 네임스페이스 선언을 제거했기 때문에 파일은 약 7% 더 작았습니다. SmartArt 데이터 및 레이아웃 파트, 최신 주석 파트, 애니메이션 타이밍 XML은 바이트 단위로 동일했습니다. 이는 개수 일치보다 강한 증거입니다. 파트가 재생성된 것이 아니라 그대로 전달되었습니다.
어떤 프레젠테이션에서든 첫 번째 계층은 다음과 같이 재현할 수 있습니다:
import zipfile
before = zipfile.ZipFile("original.pptx")
after = zipfile.ZipFile("saved.pptx")
print(sorted(set(before.namelist()) ^ set(after.namelist()))) # [] = no parts added or lost
빈 목록은 저렴한 첫 확인 방법입니다. 비어 있지 않다면 파일을 신뢰하기 전에 차이가 나는 파트를 비교하세요.

둘째, 수정 테스트입니다. 슬라이드 2의 제목을 편집하고 텍스트 상자를 추가한 뒤 저장했습니다. 애니메이션, 전환, SmartArt, 주석, 동영상, 차트, 노트가 모두 그대로 있었고 PowerPoint는 동일한 개수에 도형 하나가 추가된 것으로 보고했습니다. python-pptx가 저장 시 애니메이션과 SmartArt를 삭제한다는 흔한 주장이 증거 앞에서 무너지는 지점입니다.
한 가지 한계: 애니메이션 정의와 구조가 유지되었고 PowerPoint가 여전히 이를 인식한다는 점은 확인했습니다. 슬라이드 쇼를 프레임 단위로 실행하지 않았으므로 애니메이션이 이전과 정확히 동일하게 재생된다고 주장하지 않습니다. 동영상도 마찬가지입니다. 미디어, 관계, 첫 프레임은 유지되었지만 여러 장치에서의 재생은 테스트하지 않았습니다.

Spire는 객체 및 렌더링 수준에서 테스트된 기능을 보존했지만 일부 OOXML 구조는 다시 작성되었습니다. 타이밍 및 SmartArt XML은 재생성되었고, 최신 주석은 이전 comment1.xml + tag1.xml 형식이 되었으며, 모든 슬라이드에 전환 요소와 함께 빈 타이밍 노드가 추가되었습니다. 주석의 작성자와 텍스트는 올바르게 전달되었지만 단일 테스트 주석에 대해 답글 스레드, 해결 상태, 공동 작업 메타데이터는 확인하지 않았습니다. PowerPoint는 예상 객체와 함께 파일을 다시 열었습니다. 그러나 패키지 레이아웃은 바이트 단위로 보존되지 않았습니다.
python-pptx가 실제로 처리하는 것
위의 왕복 결과는 python-pptx가 다양한 작업군에서 여전히 기본 선택인 이유를 설명합니다. 모델링을 잘하는 객체는 편집하고 나머지는 모두 보존합니다. 객체 모델은 실무 프레젠테이션의 표준 콘텐츠를 다룹니다:
- 텍스트, 이미지, 표, 차트, 하이퍼링크 — 일반적인 작업에 대해 읽기 및 쓰기를 지원하며, 지원 범위는 객체 유형에 따라 다릅니다. 차트 데이터를 바꾸면 포함된 통합 문서가 다시 작성됩니다.
- 발표자 노트 — 일급
NotesSlide객체입니다. - 동영상 —
add_movie는 동영상 객체를 삽입합니다. 이 API는 실험적으로 표시되어 있습니다. 크기, MIME 유형, 포스터 프레임을 직접 지정해야 하며 미디어 재생 호환성은 별개의 문제입니다. - 레이아웃에서 슬라이드 생성 —
add_slide는 마스터의 레이아웃에서 새 슬라이드를 만듭니다. 이는 템플릿 기반 생성의 핵심입니다.
이 API 표면은 가장 일반적인 자동화 패턴을 지원합니다. 고정된 기업 템플릿, 미리 정의된 레이아웃에서 슬라이드를 만들고 고객별 또는 주별로 제목, 숫자, 차트, 이미지를 채우는 스크립트, 그리고 전달을 위해 PowerPoint로 다시 가져가는 최종 파일입니다. 왕복 충실도는 바로 이 패턴에 필요합니다. 템플릿의 애니메이션과 SmartArt는 스크립트로 작성하는 것이 아니라 보존하는 것이 목적이기 때문입니다.
from pptx import Presentation
prs = Presentation("template.pptx")
slide = prs.slides[1]
title = slide.shapes.title # works regardless of localized shape names
if title is not None:
title.text = "Q3 Review"
prs.save("edited.pptx")
템플릿 사본에 대해 실행하고 결과를 다시 열어 보세요. 제목은 변경되고 파일의 나머지는 그대로입니다.

이 라이브러리는 MIT 라이선스이며 Office 설치가 필요 없고, lxml, Pillow, XlsxWriter, typing-extensions라는 작은 종속성 집합을 사용합니다. 이 중 데스크톱 애플리케이션이 필요한 것은 없습니다. 객체 모델 범위 안의 작업이라면 예측 가능하고 무료입니다.
Python PPTX 생태계: 업스트림과 포크
업스트림 패키지는 2024년 8월에 출시된 버전 1.0.2에 머물러 있으며, 그 이후 더 새로운 공식 릴리스가 없습니다. 한편 여러 포크가 업스트림 객체 모델 위에 추가 API와 워크플로를 도입했습니다. python-pptx 대안을 선택할 때 이를 이해하는 것이 좋습니다. 선택지는 "서로 다른 라이브러리"라기보다 "기능 집합이 갈라진 하나의 코드베이스"에 가깝기 때문입니다.
| 패키지 | 버전 | 성격 |
|---|---|---|
| python-pptx | 1.0.2 | 업스트림 기반, MIT |
| power-pptx | 2.15.0 | 적극적으로 유지 관리되는 포크, MIT, Python 3.10–3.15 |
| ps-python-pptx | 1.3.0 | 테마 및 배경 제어, 목록 및 서식 있는 텍스트 도우미, 대체 텍스트, 도형 z 순서, 슬라이드 지우기 API를 추가한 포크 |
| python-pptx-ng | 0.7.0 | 더 오래된 역사적 브랜치, 대체로 비활성 |
power-pptx는 업스트림 객체 모델을 유지하고 슬라이드 관리 기능인 remove, move, reorder, duplicate와 슬라이드 전환을 위한 set_transition, 레이아웃 린터, 자동 복구, HTML 가져오기 경로를 추가합니다. render_thumbnails는 슬라이드를 렌더링하지만 내장 엔진이 아니라 외부 LibreOffice 및 Poppler/PDFium 체인을 사용하므로 기능 체크박스가 아니라 배포 문제가 됩니다.
실험하기 전에 알아 둘 실용적인 함정: ps-python-pptx는 업스트림 패키지와 동일한 pptx 가져오기 이름을 노출합니다. 한 환경에 둘 다 설치해도 둘 다 사용할 수 없습니다. 비교하려면 별도의 가상 환경을 사용하세요.
API가 다른 지점
두 번째 섹션의 왕복 표는 "저장 후 무엇이 살아남는가"에 답합니다. 이 표는 다른 질문, 즉 각 라이브러리가 실제로 생성, 읽기, 수정할 수 있는 대상에 답합니다. 두 가지를 분리해서 보세요. 테스트에서 python-pptx는 API가 없는 모든 객체 유형을 보존했습니다.
프레젠테이션 작성
| 기능 | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| 텍스트, 이미지, 표, 차트, 하이퍼링크 | 기본 지원 | 기본 지원 | 기본 지원 |
| 발표자 노트 | 기본 지원 | 기본 지원 | 기본 지원 |
| 동영상 삽입 | 실험적(add_movie), 수동 크기 조정 및 포스터 프레임 |
기본 지원 | 기본 지원(InsertVideo) |
| 새 슬라이드 | 기본 지원 | 기본 지원 | 기본 지원 |
| 슬라이드 삭제 / 순서 변경 / 복제 | 없음 | remove / move / reorder / duplicate |
기본 지원 |
| 도형 애니메이션 | 없음 | 없음 | 기본 지원(Timeline) |
| 슬라이드 전환 | 없음 | set_transition |
기본 지원(SlideShowTransition) |
| SmartArt 생성 | 없음 | 없음 | 기본 지원(InsertSmartArt) |
| 주석 | 없음 | 없음 | 기본 지원(AddComment / DeleteComment) |
문서 처리
| 기능 | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| 기존 PPTX 열기 및 편집 | 기본 지원 | 기본 지원 | 기본 지원 |
| PDF / 이미지 / SVG / HTML 내보내기 | 없음 | render_thumbnails(외부 런타임) |
기본 지원(PDF / 이미지 / SVG / HTML) |
| 프레젠테이션 병합 / 분할 | 수동 XML 및 관계 복사 | duplicate 도우미, 병합은 여전히 수동 |
기본 지원 |
| 암호화 / 암호 보호 | 없음 | 없음 | 기본 지원(Encrypt / Protect) |
| 디지털 서명 | 없음 | 없음 | 읽기 / 검증 / 제거, 생성은 검사에서 확인되지 않음 |
두 행은 솔직하게 설명할 필요가 있습니다. 워터마킹은 세 제품 모두 전용 워터마크 API를 제공하지 않으므로 표에 포함되지 않았습니다. PowerPoint 자체에 기본 제공 워터마크 기능이 없으며, 실제 방법(도형을 배치한 뒤 텍스트나 이미지로 채우기)은 세 라이브러리 모두에서 사용할 수 있습니다. 디지털 서명은 확인할 수 있었던 읽기/검증/제거만 표시했습니다. 생성 기능이 있다고 주장하지 않습니다.
표들을 서로 대조해 보세요. python-pptx와 power-pptx가 "없음"으로 표시한 기능은 우리의 왕복 테스트에서 그대로 살아남은 객체 유형과 정확히 일치합니다. 빠진 것은 안전성이 아니라 작업을 수행할 핸들입니다.
그 격차를 메우는 비용
바이트 수준 보존이 라이브러리를 더 유능하게 만들지도, API가 없다고 해서 파괴적으로 만들지도 않습니다. 격차가 중요한지는 전적으로 파이프라인에 요구되는 작업에 달려 있습니다.
프레젠테이션이 고정 템플릿으로 만들어지고 Python이 제목, 숫자, 이미지만 교체하며, 애니메이션이 있는 최종 파일을 전달을 위해 PowerPoint로 되돌려 보내는 경우 python-pptx가 이미 적합하며 "누락된" API는 문제되지 않습니다. 보존되지만 건드리지 않는 것이 바로 원하는 동작입니다.
격차는 기능 자체를 생성하거나 변환해야 할 때 실제 비용이 됩니다. 생성된 슬라이드의 애니메이션 작성, 프레젠테이션 일괄 순서 변경, SmartArt 프로그래밍 방식 구축, 승인 시스템의 검토 주석 추가, 데스크톱 Office 없이 완성된 프레젠테이션을 PDF나 이미지로 내보내기, 출력 파일 보호 등입니다. 이제 표의 모든 "없음"은 다음 우회 방법 중 하나로 바뀝니다:
| 접근 방식 | 추가 종속성 | 지속적 유지 관리 |
|---|---|---|
| 패키지에 대한 원시 XML 패치 | lxml, OOXML 사양 지식 | PowerPoint 형식이 개정될 때마다 직접 작성한 타이밍 또는 SmartArt XML이 깨질 수 있음 |
| 렌더링을 위한 헤드리스 LibreOffice | LibreOffice plus Poppler 또는 PDFium | 버전 드리프트, 프로필 격리, PowerPoint와의 렌더링 차이 |
| Office COM 자동화 | 라이선스가 있는 데스크톱 Office 설치 | Windows 전용, 단일 인스턴스 처리량, 부하 시 COM 실패 |
| 변환 또는 보호 단계마다 별도 도구 | 단계마다 종속성 하나 추가 | 글루 코드, 예외 표면, 파일 핸드오프 |
이들 각각은 합당한 엔지니어링 선택이며, 팀들은 매일 프로덕션에서 실행합니다. 회계적 질문은 그 스택(XML 패치, LibreOffice 컨테이너, COM 세션 풀)을 제품의 일부로 소유할지, 아니면 제품 주변의 인프라로 둘지입니다. 유용한 사고 모델: 오픈 소스 라이브러리는 복잡성을 여러분의 통합 코드로 옮기고, 상용 라이브러리는 라이선스하는 종속성으로 옮깁니다.
더 완전한 프레젠테이션 API 사용
요구 사항(마케팅이 아니라)이 상용 라이브러리를 고려하게 만드는 지점입니다. E-iceblue의 자체 상용 라이브러리인 Spire.Presentation for Python은 오픈 소스 패키지가 담고 있지만 모델링하지 않는 객체 유형인 애니메이션 타임라인, 전환, SmartArt, 주석, 암호화, 렌더링 내보내기를 노출합니다.
차이는 파이프라인이 더 이상 필요로 하지 않는 것에서 드러납니다. "편집은 python-pptx, 렌더링은 LibreOffice, 애니메이션 추가는 COM 스크립트"가 필요했던 워크플로가 단일 객체 모델로 축소될 수 있습니다:
from spire.presentation import (
Presentation, FileFormat, AnimationEffectType, TransitionType,
)
from spire.presentation.common import PointF, DateTime
pres = Presentation()
pres.LoadFromFile("input.pptx")
# Move the slide at index 1 to index 3. The signature is Move(newIndex, oldIndex).
pres.Slides.Move(3, 1)
first = pres.Slides[0]
first.Timeline.MainSequence.AddEffect(first.Shapes[0], AnimationEffectType.Fade) # demo: choose your target shape
first.SlideShowTransition.Type = TransitionType.Fade
author = pres.CommentAuthors.AddAuthor("Reviewer", "RV")
first.AddComment(
author,
"Check the Q3 figures.",
PointF(100.0, 100.0), # PointF takes floats, not ints
DateTime.Parse("2026-11-23 10:00:00"), # DateTime has no Now(); parse a string
)
pres.SaveToFile("output.pdf", FileFormat.PDF)
pres.Encrypt("demo-password")
pres.SaveToFile("output.pptx", FileFormat.Pptx2013)
pres.Dispose()
실행 결과 PowerPoint는 편집된 파일을 12개 슬라이드, 3개 애니메이션 시퀀스, 2개 주석, 2개 전환 슬라이드로 다시 열었습니다. 원본 파일에 각각 정확히 하나씩 추가된 것입니다. 새 주석의 텍스트와 작성자는 다시 열었을 때 읽을 수 있었고, Fade 전환은 첫 번째 슬라이드에 연결되었습니다.
PDF와 암호화된 PPTX는 별도의 출력입니다. PDF는 암호화 전에 내보내지고, 암호는 이후에 저장되는 PPTX에만 적용됩니다.
같은 API 제품군은 인접 작업도 다룹니다. 여러 프레젠테이션을 하나로 병합하고, 파일을 편집하는 동일한 프로세스에서 PowerPoint를 PDF로 변환하며, 결과를 암호로 보호합니다. 표에서 표시한 객체인 애니메이션, SmartArt 다이어그램, 주석은 동일한 객체 모델에서 처리됩니다.
이것은 "오픈 소스는 실패한다"는 뜻이 아닙니다. 증거는 반대를 보여 줍니다. 오픈 소스 경로는 실제적이고 흔한 작업 유형을 잘 처리합니다. 상용 라이브러리는 작업 목록 자체가 넓어질 때 제 역할을 하며, 그 대안은 애초에 그런 작업을 위해 설계되지 않은 라이브러리 주변에 여러 통합 계층을 유지하는 것입니다.
배포 및 라이선스 고려 사항
python-pptx, power-pptx, ps-python-pptx는 모두 MIT 라이선스입니다. 배포는 pip install이며, 핵심 PPTX 편집에는 Microsoft Office나 외부 렌더링 프로세스가 필요하지 않습니다. 숨은 비용은 다른 곳, 즉 요구 사항이 API를 초과할 때 라이브러리 주변에 구축하는 우회 계층에 있습니다(앞 섹션 참조).
Spire.Presentation은 상용 소프트웨어입니다. 비즈니스 사용은 상용 라이선스 조건에 따릅니다. 평가판 빌드는 워터마크를 추가하고 출력을 제한할 수 있으므로 위 측정에서는 워터마크를 제외했습니다. 깨끗한 테스트를 위해서는 무료 버전을 사용하거나 임시 라이선스를 신청하세요. 상용 조건과 배포 옵션은 라이선스 페이지에서 확인할 수 있습니다. 런타임에는 배포 고려 사항도 따릅니다. 대상 환경(Linux 서버, 컨테이너, Windows)에 대해 지원되는 플랫폼을 제품의 현재 요구 사항과 대조해 확인하세요.
프로젝트에 맞는 접근 방식 선택
페르소나 목록 대신 결정 경로를 제시합니다. 각 분기는 위의 증거에서 직접 이어집니다:
- 표준 슬라이드 콘텐츠를 생성하거나 수정합니다 — 텍스트, 이미지, 표, 차트, 노트, 하이퍼링크, 동영상을 이미 애니메이션과 SmartArt가 포함된 템플릿 안에서 다룹니다. python-pptx로 충분합니다. 왕복 보존이 검증되었고 종속성이 최소이며 누락된 API가 이 작업을 막지 않습니다. 나중에 슬라이드를 삭제, 순서 변경, 복제하거나 전환을 설정해야 한다면 동일한 테스트로 power-pptx를 평가하세요.
- 슬라이드를 채우는 것만이 아니라 만들어야 합니다. 애니메이션, SmartArt, 주석이 템플릿의 산출물이 아니라 파이프라인의 출력입니다. 해당 API를 갖춘 라이브러리를 평가하거나, 이를 대체할 XML 패치 작업을 예산에 포함하세요.
- 파이프라인이 다른 형식이나 잠긴 파일로 끝납니다. 데스크톱 Office 설치 없이 PDF, 이미지 또는 암호로 보호된 출력을 만들어야 합니다. 기본 변환 및 보호 기능이 있는 라이브러리를 평가하거나 LibreOffice와 암호화 도구를 명시적으로 계획하세요.
무엇을 선택하든 자체 프레젠테이션에 동일한 테스트를 실행하세요. 열기, 저장, 객체 수 세기, 렌더링 차이 비교. 어떤 기능 표보다 더 많은 답을 줍니다. Spire를 또 다른 후보로 추가하려면 Spire.Presentation 제품 페이지와 다운로드 패키지가 합리적인 출발점입니다. 작업이 python-pptx의 객체 모델 안에 머문다면 테스트가 그 사실도 알려 줄 것입니다.
함께 보기
Scegliere una libreria Python PPTX per file PowerPoint reali
Indice dei contenuti
- Cosa c'è dentro un file PPTX
- Risultati del test di andata e ritorno
- Cosa gestisce realmente python-pptx
- Upstream e fork
- Confronto della copertura delle API
- Il costo di colmare queste lacune
- Un'API di presentazione più completa
- Considerazioni su deployment e licenze
- Scegliere un approccio per il tuo progetto

Apri un file .pptx con uno strumento ZIP e troverai molto più delle sole diapositive: un grafico supportato da una cartella di lavoro Excel incorporata, un diagramma SmartArt suddiviso in cinque parti del pacchetto, XML di temporizzazione delle animazioni, definizioni di transizione, note del relatore, commenti moderni, un video incorporato e relazioni di collegamento ipertestuale. Qualsiasi libreria Python per PPTX deve decidere cosa fare con tutto questo, non solo con le caselle di testo che volevi modificare.
La maggior parte dei confronti si ferma agli elenchi delle funzionalità e lascia intendere che tutto ciò che non ha una casella di spunta venga distrutto al salvataggio. Abbiamo verificato questa ipotesi con un file PowerPoint di 12 diapositive contenente tali oggetti, eseguito attraverso ciascuna libreria e misurato a livello di pacchetto, oggetto e pixel.
Il risultato separa due questioni. Preservazione: python-pptx conserva ciò che non è in grado di toccare, il che lo rende affidabile per un'ampia classe di lavori di modifica. Capacità: il divario si apre quando un progetto deve creare o manipolare quegli oggetti. Questo articolo presenta prima le prove, poi mappa dove arriva ciascuna API.
Un file PowerPoint è più delle sue diapositive visibili
Il nostro file di test è stato generato con PowerPoint stesso tramite automazione COM, non assemblato a mano, quindi fornisce un campione di test rappresentativo con una serie di oggetti presenti nelle presentazioni del mondo reale. Ha 12 diapositive e 35 elementi forma: una diapositiva di titolo, testo del corpo con un collegamento ipertestuale esterno, una tabella 4×3, un grafico a colonne supportato da un file .xlsx incorporato, un'immagine, una forma raggruppata, un diagramma SmartArt, due forme animate con una transizione Fade, note del relatore, un commento di revisione moderno, un video incorporato e un collegamento interno alla pagina.
Decompresso, si tratta di 81 parti del pacchetto e circa 100 KB. La maggior parte di queste parti è invisibile al lettore ma portante per la presentazione: l'XML di temporizzazione per la diapositiva animata, l'XML di transizione, le cinque parti SmartArt (dati, layout, stile rapido, colori e disegno), la parte del commento con i metadati dell'autore, il file multimediale per il video.

Questo è importante per la scelta della libreria perché il formato OOXML non ha una "modalità sicura". Quando una libreria apre un pacchetto, lo riscrive e lo salva, ognuna di quelle parti è in gioco. La domanda non è mai solo "può aggiungere una casella di testo". È "cosa fa alle 80 parti che non gli sono state chieste".
Cosa succede quando Python salva un PPTX esistente?
Abbiamo aperto il file con python-pptx 1.0.2, power-pptx 2.15.0 e Spire.Presentation per Python 11.8.1 (valutazione), salvato senza modifiche e verificato tre livelli: la struttura del pacchetto ZIP, il modello a oggetti che PowerPoint stesso riporta tramite COM e un confronto a livello di pixel di tutte le 12 diapositive renderizzate dallo stesso motore PowerPoint a 1280×720. Spire.Presentation è un prodotto di E-iceblue e questo test è stato eseguito dall'editore; i risultati grezzi sono riportati di seguito, inclusi i casi in cui i risultati sono meno lusinghieri per Spire.
| Metrica | Originale | python-pptx | power-pptx | Spire |
|---|---|---|---|---|
| Diapositive | 12 | 12 | 12 | 12 |
| Forme | 35 † | 35 | 35 | 35 |
| Sequenze di animazione | 2 | 2 | 2 | 2 |
| Diapositive con una transizione | 1 | 1 | 1 | 1 |
| Nodi SmartArt | 5 | 5 | 5 | 5 |
| Commenti | 1 | 1 | 1 | 1 |
| Video / grafico / tabella / note | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 |
| Riferimenti a relazioni interrotti | 0 | 0 | 0 | 0 |
| Differenza di pixel renderizzati | — | 0,000% | 0,000% | 0,000% |
† Gli elementi forma sono conteggiati dall'XML della diapositiva. Due di essi si trovano all'interno di un gruppo, quindi il conteggio delle forme di primo livello di PowerPoint è 33 per ogni file; il test di modifica qui sotto riporta 34 perché abbiamo aggiunto una casella di testo.
Due dettagli valgono più della tabella.
In primo luogo, python-pptx e power-pptx non hanno aggiunto né perso parti. I loro file erano circa il 7% più piccoli perché la ri-serializzazione ha eliminato gli spazi bianchi e le dichiarazioni di namespace ripetute; le parti dati e layout di SmartArt, la parte del commento moderno e l'XML di temporizzazione delle animazioni erano identici byte per byte. Questo è più forte della corrispondenza dei conteggi: le parti sono state trasportate, non rigenerate.
Puoi riprodurre quel primo livello su qualsiasi presentazione:
import zipfile
before = zipfile.ZipFile("original.pptx")
after = zipfile.ZipFile("saved.pptx")
print(sorted(set(before.namelist()) ^ set(after.namelist()))) # [] = no parts added or lost
Un elenco vuoto è il controllo iniziale più economico; se non è vuoto, confronta le parti diverse prima di fidarti del file.

In secondo luogo, il test di modifica. Abbiamo modificato un titolo nella diapositiva 2, aggiunto una casella di testo e salvato. Animazioni, transizione, SmartArt, commento, video, grafico e note erano ancora tutti presenti, e PowerPoint ha riportato gli stessi conteggi più una forma. È qui che l'affermazione comune secondo cui python-pptx elimina animazioni e SmartArt al salvataggio fallisce di fronte alle prove.
Un limite: abbiamo verificato che le definizioni e le strutture delle animazioni siano sopravvissute e che PowerPoint le riconosca ancora. Non abbiamo eseguito una presentazione fotogramma per fotogramma, quindi non affermiamo che le animazioni si riproducano esattamente come prima. Lo stesso vale per il video: media, relazioni e primo fotogramma sono sopravvissuti; la riproduzione su diversi dispositivi non è stata testata.

Spire ha preservato le funzionalità testate a livello di oggetto e di rendering, sebbene alcune strutture OOXML siano state riscritte: l'XML di temporizzazione e SmartArt è stato rigenerato, il commento moderno è diventato il formato più vecchio comment1.xml + tag1.xml, e nodi di temporizzazione vuoti sono stati aggiunti a ogni diapositiva insieme agli elementi di transizione. L'autore e il testo del commento sono stati riportati correttamente, ma non abbiamo verificato thread di risposta, stati risolti o metadati di collaborazione per un singolo commento di test. PowerPoint ha riaperto il file con gli oggetti attesi; il layout del pacchetto, tuttavia, non è stato preservato byte per byte.
Cosa gestisce realmente python-pptx
Il risultato del test di andata e ritorno sopra spiega perché python-pptx rimane la scelta predefinita per un'intera famiglia di lavori: modifica bene gli oggetti che modella e preserva tutto il resto. Il suo modello a oggetti copre il contenuto standard di una presentazione funzionante:
- Testo, immagini, tabelle, grafici e collegamenti ipertestuali — lettura e scrittura per le operazioni comuni, con una copertura che varia per tipo di oggetto; la sostituzione dei dati del grafico riscrive la cartella di lavoro incorporata.
- Note del relatore — un oggetto
NotesSlidedi prima classe. - Video —
add_movieinserisce un oggetto video. L'API è contrassegnata come sperimentale: specifichi tu stesso le dimensioni, il tipo MIME e il fotogramma di anteprima, e la compatibilità di riproduzione dei media è una questione separata. - Diapositive da layout —
add_slidecrea nuove diapositive dai layout del master, che è la spina dorsale della generazione guidata da modelli.
Questa superficie API supporta il modello di automazione più comune: un modello aziendale fisso, uno script che crea diapositive da layout predefiniti e compila titoli, numeri, grafici e immagini per cliente o per settimana, e un file finale che torna in PowerPoint per la consegna. La fedeltà di andata e ritorno è esattamente ciò di cui questo modello ha bisogno, perché le animazioni e lo SmartArt del modello devono essere preservati, non scriptati.
from pptx import Presentation
prs = Presentation("template.pptx")
slide = prs.slides[1]
title = slide.shapes.title # works regardless of localized shape names
if title is not None:
title.text = "Q3 Review"
prs.save("edited.pptx")
Eseguilo su una copia del tuo modello e riapri il risultato: il titolo cambia e il resto del file rimane intatto.

La libreria è distribuita con licenza MIT, non richiede l'installazione di Office e utilizza un piccolo insieme di dipendenze — lxml, Pillow, XlsxWriter, typing-extensions — nessuna delle quali richiede un'applicazione desktop. Per i lavori all'interno del suo modello a oggetti, è prevedibile e gratuita.
L'ecosistema Python PPTX: upstream e fork
Il pacchetto upstream rimane alla versione 1.0.2, rilasciata in agosto 2024, senza rilasci formali più recenti da allora. Nel frattempo, diversi fork hanno introdotto API e flussi di lavoro aggiuntivi sopra il modello a oggetti upstream. Vale la pena comprenderlo se stai scegliendo un'alternativa a python-pptx, perché le opzioni sono meno "librerie diverse" e più "un'unica base di codice con insiemi di funzionalità divergenti".
| Pacchetto | Versione | Posizione |
|---|---|---|
| python-pptx | 1.0.2 | La base upstream, MIT |
| power-pptx | 2.15.0 | Un fork attivamente mantenuto, MIT, Python 3.10–3.15 |
| ps-python-pptx | 1.3.0 | Un fork che aggiunge controllo di tema e sfondo, helper per elenchi e testo formattato, testo alternativo, ordine z delle forme e API per svuotare le diapositive |
| python-pptx-ng | 0.7.0 | Un ramo storico più vecchio, in gran parte inattivo |
power-pptx mantiene il modello a oggetti upstream e aggiunge la gestione delle diapositive — remove, move, reorder, duplicate — oltre a set_transition per le transizioni delle diapositive, un linter per i layout, la riparazione automatica e un percorso di importazione HTML. Il suo render_thumbnails esegue il rendering delle diapositive, ma tramite una catena esterna LibreOffice e Poppler/PDFium anziché un motore integrato, il che diventa una questione di deployment piuttosto che una casella di funzionalità.
Una trappola pratica da conoscere prima di sperimentare: ps-python-pptx espone lo stesso nome di importazione pptx del pacchetto upstream. Installarli entrambi in un unico ambiente non ti darà entrambi; usa ambienti virtuali separati quando vuoi confrontarli.
Dove le API differiscono
La tabella di andata e ritorno nella seconda sezione risponde a "cosa sopravvive a un salvataggio". Questa tabella risponde a una domanda diversa: cosa ciascuna libreria può attivamente creare, leggere e modificare. Tieni separate le due cose — nel nostro test, python-pptx ha preservato ogni tipo di oggetto per cui non ha un'API.
Creazione di presentazioni
| Funzionalità | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Testo, immagini, tabelle, grafici, collegamenti ipertestuali | Nativo | Nativo | Nativo |
| Note del relatore | Nativo | Nativo | Nativo |
| Inserimento video | Sperimentale (add_movie); dimensionamento e fotogramma di anteprima manuali |
Nativo | Nativo (InsertVideo) |
| Nuove diapositive | Nativo | Nativo | Nativo |
| Elimina / riordina / duplica diapositive | No | remove / move / reorder / duplicate |
Nativo |
| Animazioni delle forme | No | No | Nativo (Timeline) |
| Transizioni delle diapositive | No | set_transition |
Nativo (SlideShowTransition) |
| Creazione SmartArt | No | No | Nativo (InsertSmartArt) |
| Commenti | No | No | Nativo (AddComment / DeleteComment) |
Elaborazione dei documenti
| Funzionalità | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Aprire e modificare un PPTX esistente | Nativo | Nativo | Nativo |
| Esportazione PDF / immagine / SVG / HTML | No | render_thumbnails (runtime esterno) |
Nativo (PDF / immagine / SVG / HTML) |
| Unire / dividere presentazioni | Copia manuale di XML e relazioni | Helper duplicate; l'unione rimane manuale |
Nativo |
| Crittografia / protezione con password | No | No | Nativo (Encrypt / Protect) |
| Firme digitali | No | No | Lettura / verifica / rimozione; creazione non trovata nella nostra ispezione |
Due righe richiedono un'inquadratura onesta. La filigrana non compare nella matrice perché nessuna delle tre offre un'API dedicata alla filigrana — PowerPoint stesso non ha una funzione di filigrana integrata, e l'approccio pratico (posizionare una forma, quindi riempirla con testo o un'immagine) è disponibile in tutte e tre le librerie. Le firme digitali compaiono solo come lettura/verifica/rimozione perché è ciò che abbiamo potuto confermare; non affermiamo la capacità di crearle.
Nota come le tabelle si leggono l'una rispetto all'altra. Le funzionalità in cui python-pptx e power-pptx mostrano "No" sono precisamente i tipi di oggetto che sono sopravvissuti intatti al nostro test di andata e ritorno. Ciò che manca non è la sicurezza — è il manico per fare il lavoro.
Il costo di colmare queste lacune
La preservazione a livello di byte non rende una libreria più capace, e un'API assente non la rende distruttiva. Se il divario conta dipende interamente da ciò che viene chiesto alla tua pipeline.
Se le tue presentazioni sono costruite da modelli fissi e Python scambia solo titoli, numeri e immagini — con il file finale animato riconsegnato a PowerPoint per la consegna — python-pptx è già adatto, e le sue API "mancanti" non emergono mai. Preservato-ma-intatto è esattamente il comportamento che desideri.
Il divario diventa un costo reale quando il requisito è generare o trasformare le funzionalità stesse: creare animazioni per le diapositive generate, riordinare in batch le presentazioni, costruire SmartArt a livello di programmazione, aggiungere commenti di revisione da un sistema di approvazione, esportare presentazioni finite in PDF o immagini senza un Office desktop, o proteggere i file di output. Ora ogni "No" nella matrice si converte in una di queste soluzioni alternative:
| Approccio | Dipendenza extra | Manutenzione continua |
|---|---|---|
| Patch XML grezze sul pacchetto | lxml, conoscenza della specifica OOXML | Ogni revisione del formato PowerPoint può rompere l'XML di temporizzazione o SmartArt scritto a mano |
| LibreOffice headless per il rendering | LibreOffice più Poppler o PDFium | Deriva delle versioni, isolamento dei profili, differenze di rendering rispetto a PowerPoint |
| Automazione COM di Office | Un'installazione di Office desktop con licenza | Solo Windows, throughput a istanza singola, errori COM sotto carico |
| Uno strumento separato per ogni passaggio di conversione o protezione | Una dipendenza in più ciascuno | Codice di collegamento, superfici di eccezione, passaggi di file |
Ognuno di questi è una scelta ingegneristica legittima, e i team li eseguono in produzione ogni giorno. La domanda contabile è se vuoi possedere quello stack — le patch XML, il container LibreOffice, il pool di sessioni COM — come parte del tuo prodotto, o come infrastruttura attorno ad esso. Un modello mentale utile: le librerie open source spostano la complessità nel tuo codice di integrazione, mentre una libreria commerciale la sposta in una dipendenza che concedi in licenza.
Lavorare con un'API di presentazione più completa
Questo è il punto in cui i requisiti — non il marketing — portano una libreria commerciale in scena. Spire.Presentation per Python, la libreria commerciale di E-iceblue, espone i tipi di oggetto che i pacchetti open source trasportano ma non modellano: timeline di animazione, transizioni, SmartArt, commenti, crittografia ed esportazioni di rendering.
La differenza si manifesta in ciò di cui una pipeline smette di aver bisogno. Un flusso di lavoro che prima richiedeva "python-pptx per modificare, LibreOffice per renderizzare, uno script COM per aggiungere animazioni" può ridursi a un unico modello a oggetti:
from spire.presentation import (
Presentation, FileFormat, AnimationEffectType, TransitionType,
)
from spire.presentation.common import PointF, DateTime
pres = Presentation()
pres.LoadFromFile("input.pptx")
# Move the slide at index 1 to index 3. The signature is Move(newIndex, oldIndex).
pres.Slides.Move(3, 1)
first = pres.Slides[0]
first.Timeline.MainSequence.AddEffect(first.Shapes[0], AnimationEffectType.Fade) # demo: choose your target shape
first.SlideShowTransition.Type = TransitionType.Fade
author = pres.CommentAuthors.AddAuthor("Reviewer", "RV")
first.AddComment(
author,
"Check the Q3 figures.",
PointF(100.0, 100.0), # PointF takes floats, not ints
DateTime.Parse("2026-11-23 10:00:00"), # DateTime has no Now(); parse a string
)
pres.SaveToFile("output.pdf", FileFormat.PDF)
pres.Encrypt("demo-password")
pres.SaveToFile("output.pptx", FileFormat.Pptx2013)
pres.Dispose()
Nella nostra esecuzione, PowerPoint ha riaperto il file modificato come 12 diapositive con tre sequenze di animazione, due commenti e due diapositive con transizione — esattamente uno di ciascuno aggiunto al file originale. Il testo e l'autore del nuovo commento erano leggibili alla riapertura, e la transizione Fade era associata alla prima diapositiva.
Il PDF e il PPTX crittografato sono output separati: il PDF viene esportato prima della crittografia, mentre la password si applica solo al PPTX salvato successivamente.
La stessa famiglia di API copre le operazioni adiacenti: unire più presentazioni in un'unica presentazione, convertire PowerPoint in PDF nello stesso processo che modifica il file, e proteggere il risultato con una password. Gli oggetti segnalati dalla nostra matrice — animazioni, diagrammi SmartArt e commenti — sono gestiti dallo stesso modello a oggetti.
Questo non significa "l'open source fallisce". Le prove mostrano il contrario: il percorso open source gestisce bene una classe di lavoro reale e comune. La libreria commerciale guadagna il suo posto quando l'elenco delle attività stesso si amplia, e l'alternativa è mantenere diversi livelli di integrazione attorno a una libreria che non è mai stata progettata per essi.
Considerazioni su deployment e licenze
python-pptx, power-pptx e ps-python-pptx sono tutti distribuiti con licenza MIT. Il deployment è un pip install; la modifica principale di PPTX non richiede Microsoft Office né un processo di rendering esterno. Il costo nascosto si trova altrove — nei livelli di soluzione alternativa che costruisci attorno alla libreria quando un requisito supera la sua API, come descritto nella sezione precedente.
Spire.Presentation è software commerciale: l'uso aziendale rientra nei termini della sua licenza commerciale. Le build di valutazione aggiungono una filigrana e possono limitare l'output, quindi le misurazioni sopra escludono la filigrana; usa la edizione gratuita o richiedi una licenza temporanea per un test pulito. I termini commerciali e le opzioni di deployment sono nella pagina delle licenze. Il suo runtime comporta anche considerazioni sul deployment: verifica le piattaforme supportate per il tuo ambiente di destinazione (server Linux, container, Windows) rispetto ai requisiti attuali del prodotto.
Scegliere un approccio per il tuo progetto
Invece di un elenco di profili, un percorso decisionale — ogni ramo deriva direttamente dalle prove sopra:
- Generi o modifichi contenuto standard delle diapositive — testo, immagini, tabelle, grafici, note, collegamenti ipertestuali, video — all'interno di modelli che portano già le tue animazioni e SmartArt. python-pptx è sufficiente. La sua preservazione di andata e ritorno è verificata, le sue dipendenze sono minime e le API mancanti non bloccano mai questo lavoro. Se in seguito hai bisogno di eliminare, riordinare o duplicare diapositive, o impostare transizioni, valuta power-pptx con gli stessi test.
- Le tue diapositive devono essere create, non solo compilate. Animazioni, SmartArt e commenti sono output della tua pipeline, non artefatti di un modello. Valuta una libreria con queste API, o metti in budget il patching XML che le sostituisce.
- La pipeline termina in un altro formato o in un file bloccato. PDF, immagini o output protetto da password senza un'installazione di Office desktop. Valuta una libreria con conversione e protezione native, o pianifica esplicitamente gli strumenti LibreOffice e di crittografia.
Qualunque cosa tu scelga, esegui lo stesso test sulle tue presentazioni: apri, salva, conta gli oggetti, confronta i rendering. Risponde più di qualsiasi tabella di funzionalità. La pagina del prodotto Spire.Presentation e il suo pacchetto di download sono punti di partenza ragionevoli se vuoi aggiungere Spire come altro candidato; se il tuo lavoro rimane all'interno del modello a oggetti di python-pptx, il test te lo dirà anche.
Vedi anche
Choisir une bibliothèque Python PPTX pour de vrais fichiers PowerPoint
Table des matières
- Ce que contient réellement un fichier PPTX
- Résultats du test d'aller-retour
- Ce que python-pptx gère réellement
- Projet amont et forks
- Comparaison de la couverture des API
- Le coût de la combler des lacunes
- Une API de présentation plus complète
- Considérations de déploiement et de licence
- Choisir une approche pour votre projet

Ouvrez un fichier .pptx avec un outil ZIP et vous découvrirez bien plus que des diapositives : un graphique adossé à un classeur Excel intégré, un diagramme SmartArt réparti sur cinq parties de paquet, du XML de minutage des animations, des définitions de transitions, des notes du présentateur, des commentaires modernes, une vidéo intégrée et des relations de liens hypertexte. Toute bibliothèque Python PPTX doit décider quoi faire de tout cela, et pas seulement des zones de texte que vous veniez modifier.
La plupart des comparatifs s'arrêtent à des listes de fonctionnalités et laissent entendre que tout ce qui n'a pas de case cochée est détruit lors de l'enregistrement. Nous avons testé cette hypothèse avec un fichier PowerPoint de 12 diapositives contenant ces objets, en le faisant passer par chaque bibliothèque et en mesurant au niveau du paquet, de l'objet et du pixel.
Le résultat sépare deux questions. La préservation : python-pptx conserve ce qu'il ne peut pas modifier, ce qui le rend fiable pour une large classe de tâches d'édition. La capacité : l'écart se creuse lorsqu'un projet doit créer ou manipuler ces objets. Cet article présente d'abord les preuves, puis cartographie la portée de chaque API.
Un fichier PowerPoint, c'est plus que ses diapositives visibles
Notre fichier de test a été généré avec PowerPoint lui-même via l'automatisation COM, et non assemblé à la main ; il constitue donc un cas de test représentatif, avec une variété d'objets que l'on trouve dans de vraies présentations. Il comprend 12 diapositives et 35 éléments de forme : une diapositive de titre, du texte de corps avec un lien hypertexte externe, un tableau 4×3, un graphique en colonnes adossé à un fichier .xlsx intégré, une image, une forme groupée, un diagramme SmartArt, deux formes animées avec une transition en fondu, des notes du présentateur, un commentaire de révision moderne, une vidéo intégrée et un lien de saut interne à la page.
Décompressé, cela représente 81 parties de paquet et environ 100 Ko. La plupart de ces parties sont invisibles pour le lecteur mais essentielles à la présentation : le XML de minutage de la diapositive animée, le XML de transition, les cinq parties SmartArt (données, disposition, style rapide, couleurs et dessin), la partie de commentaire avec les métadonnées de l'auteur, le fichier média de la vidéo.

Cela compte pour le choix d'une bibliothèque, car le format OOXML n'a pas de « mode sans échec ». Lorsqu'une bibliothèque ouvre un paquet, le réécrit et l'enregistre, chacune de ces parties est concernée. La question n'est jamais seulement « peut-elle ajouter une zone de texte ». C'est « que fait-elle des 80 parties qu'on ne lui a pas demandées ».
Que se passe-t-il lorsque Python enregistre un PPTX existant ?
Nous avons ouvert le fichier avec python-pptx 1.0.2, power-pptx 2.15.0 et Spire.Presentation for Python 11.8.1 (version d'évaluation), l'avons enregistré sans modification, puis audité trois niveaux : la structure du paquet ZIP, le modèle objet que PowerPoint lui-même rapporte via COM, et une comparaison pixel par pixel des 12 diapositives rendues par le même moteur PowerPoint en 1280×720. Spire.Presentation est un produit d'E-iceblue, et ce test a été réalisé par l'éditeur ; les résultats bruts sont rapportés ci-dessous, y compris lorsqu'ils sont moins flatteurs pour Spire.
| Indicateur | Original | python-pptx | power-pptx | Spire |
|---|---|---|---|---|
| Diapositives | 12 | 12 | 12 | 12 |
| Formes | 35 † | 35 | 35 | 35 |
| Séquences d'animation | 2 | 2 | 2 | 2 |
| Diapositives avec transition | 1 | 1 | 1 | 1 |
| Nœuds SmartArt | 5 | 5 | 5 | 5 |
| Commentaires | 1 | 1 | 1 | 1 |
| Vidéo / graphique / tableau / notes | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 |
| Références de relation rompues | 0 | 0 | 0 | 0 |
| Différence de pixels au rendu | — | 0,000 % | 0,000 % | 0,000 % |
† Les éléments de forme sont comptés à partir du XML de la diapositive. Deux d'entre eux se trouvent dans un groupe, de sorte que le nombre de formes de premier niveau de PowerPoint est de 33 pour tous les fichiers ; le test de modification ci-dessous indique 34 car nous avons ajouté une zone de texte.
Deux détails valent plus que le tableau.
Premièrement, python-pptx et power-pptx n'ont ajouté ni perdu aucune partie. Leurs fichiers étaient environ 7 % plus petits parce que la re-sérialisation a supprimé les espaces blancs et les déclarations d'espace de noms répétées ; les parties de données et de disposition SmartArt, la partie de commentaire moderne et le XML de minutage des animations étaient identiques octet pour octet. C'est plus fort qu'une simple correspondance des décomptes : les parties ont été transportées, pas régénérées.
Vous pouvez reproduire ce premier niveau sur n'importe quel jeu de diapositives :
import zipfile
before = zipfile.ZipFile("original.pptx")
after = zipfile.ZipFile("saved.pptx")
print(sorted(set(before.namelist()) ^ set(after.namelist()))) # [] = no parts added or lost
Une liste vide est la vérification rapide de premier niveau ; si elle n'est pas vide, comparez les parties divergentes avant de faire confiance au fichier.

Deuxièmement, le test de modification. Nous avons modifié un titre sur la diapositive 2, ajouté une zone de texte et enregistré. Les animations, la transition, SmartArt, le commentaire, la vidéo, le graphique et les notes étaient tous toujours présents, et PowerPoint rapportait les mêmes décomptes plus une forme. C'est ici que l'affirmation courante selon laquelle python-pptx supprime les animations et SmartArt lors de l'enregistrement est contredite par les faits.
Une limite : nous avons vérifié que les définitions et structures d'animation ont survécu et que PowerPoint les reconnaît toujours. Nous n'avons pas exécuté un diaporama image par image, nous ne prétendons donc pas que les animations se jouent exactement comme avant. Il en va de même pour la vidéo : le média, les relations et la première image ont survécu ; la lecture sur différents appareils n'a pas été testée.

Spire a préservé les fonctionnalités testées aux niveaux objet et rendu, bien que certaines structures OOXML aient été réécrites : le XML de minutage et celui de SmartArt ont été régénérés, le commentaire moderne est devenu l'ancien format comment1.xml + tag1.xml, et des nœuds de minutage vides ont été ajoutés à chaque diapositive, ainsi que des éléments de transition. L'auteur et le texte du commentaire ont été correctement restitués, mais nous n'avons pas vérifié les fils de réponse, les états résolus ni les métadonnées de collaboration d'un unique commentaire de test. PowerPoint a rouvert le fichier avec les objets attendus ; la structure du paquet, toutefois, n'a pas été préservée octet pour octet.
Ce que python-pptx gère réellement
Le résultat de l'aller-retour ci-dessus explique pourquoi python-pptx reste le choix par défaut pour toute une famille de tâches : il modifie bien les objets qu'il modélise et préserve tout le reste. Son modèle objet couvre le contenu standard d'un jeu de diapositives de travail :
- Texte, images, tableaux, graphiques et liens hypertexte — lecture et écriture pour les opérations courantes, la couverture variant selon le type d'objet ; le remplacement des données d'un graphique réécrit le classeur intégré.
- Notes du présentateur — un objet
NotesSlidede première classe. - Vidéo —
add_movieinsère un objet vidéo. L'API est marquée expérimentale : vous spécifiez vous-même la taille, le type MIME et l'image d'aperçu, et la compatibilité de lecture des médias est une question distincte. - Diapositives à partir de dispositions —
add_slidecrée de nouvelles diapositives à partir des dispositions du masque, ce qui constitue l'épine dorsale de la génération pilotée par modèle.
Cette surface d'API prend en charge le schéma d'automatisation le plus courant : un modèle d'entreprise fixe, un script qui crée des diapositives à partir de dispositions prédéfinies et renseigne les titres, chiffres, graphiques et images par client ou par semaine, et un fichier final renvoyé dans PowerPoint pour la diffusion. La fidélité de l'aller-retour est exactement ce dont ce schéma a besoin, car les animations et SmartArt du modèle sont censés être préservés, pas scriptés.
from pptx import Presentation
prs = Presentation("template.pptx")
slide = prs.slides[1]
title = slide.shapes.title # works regardless of localized shape names
if title is not None:
title.text = "Q3 Review"
prs.save("edited.pptx")
Exécutez-le sur une copie de votre modèle et rouvrez le résultat : le titre change et le reste du fichier est intact.

La bibliothèque est sous licence MIT, ne nécessite aucune installation d'Office et ne tire qu'un petit ensemble de dépendances — lxml, Pillow, XlsxWriter, typing-extensions — dont aucune ne requiert d'application de bureau. Pour les tâches qui relèvent de son modèle objet, elle est prévisible et gratuite.
L'écosystème Python PPTX : projet amont et forks
Le paquet amont reste en version 1.0.2, publié en août 2024, sans nouvelle version formelle depuis. Parallèlement, plusieurs forks ont introduit des API et des flux de travail supplémentaires au-dessus du modèle objet amont. Cela vaut la peine d'être compris si vous cherchez une alternative à python-pptx, car les options sont moins « des bibliothèques différentes » que « une base de code aux fonctionnalités divergentes ».
| Paquet | Version | Position |
|---|---|---|
| python-pptx | 1.0.2 | La base amont, MIT |
| power-pptx | 2.15.0 | Un fork activement maintenu, MIT, Python 3.10–3.15 |
| ps-python-pptx | 1.3.0 | Un fork ajoutant le contrôle du thème et de l'arrière-plan, des assistants de listes et de texte enrichi, le texte de remplacement, l'ordre de superposition des formes et des API d'effacement de diapositives |
| python-pptx-ng | 0.7.0 | Une branche historique plus ancienne, largement inactive |
power-pptx conserve le modèle objet amont et ajoute la gestion des diapositives — remove, move, reorder, duplicate — ainsi que set_transition pour les transitions de diapositives, un vérificateur de disposition, une réparation automatique et un chemin d'importation HTML. Son render_thumbnails effectue le rendu des diapositives, mais via une chaîne externe LibreOffice et Poppler/PDFium plutôt qu'un moteur intégré, ce qui devient une question de déploiement plutôt qu'une case à cocher de fonctionnalité.
Un piège pratique à connaître avant d'expérimenter : ps-python-pptx expose le même nom d'import pptx que le paquet amont. Installer les deux dans un même environnement ne vous donnera pas les deux ; utilisez des environnements virtuels séparés pour les comparer.
Où les API diffèrent
Le tableau de l'aller-retour de la deuxième section répond à « ce qui survit à un enregistrement ». Ce tableau répond à une autre question : ce que chaque bibliothèque peut activement créer, lire et modifier. Gardez les deux distincts — dans notre test, python-pptx a préservé chaque type d'objet pour lequel il n'a pas d'API.
Création de présentations
| Capacité | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Texte, images, tableaux, graphiques, liens hypertexte | Natif | Natif | Natif |
| Notes du présentateur | Natif | Natif | Natif |
| Insertion de vidéo | Expérimental (add_movie) ; dimensionnement et image d'aperçu manuels |
Natif | Natif (InsertVideo) |
| Nouvelles diapositives | Natif | Natif | Natif |
| Supprimer / réorganiser / dupliquer des diapositives | Non | remove / move / reorder / duplicate |
Natif |
| Animations de formes | Non | Non | Natif (Timeline) |
| Transitions de diapositives | Non | set_transition |
Natif (SlideShowTransition) |
| Création de SmartArt | Non | Non | Natif (InsertSmartArt) |
| Commentaires | Non | Non | Natif (AddComment / DeleteComment) |
Traitement de documents
| Capacité | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Ouvrir et modifier un PPTX existant | Natif | Natif | Natif |
| Export PDF / image / SVG / HTML | Non | render_thumbnails (environnement d'exécution externe) |
Natif (PDF / image / SVG / HTML) |
| Fusionner / fractionner des présentations | Copie manuelle du XML et des relations | Assistants duplicate ; la fusion reste manuelle |
Natif |
| Chiffrement / protection par mot de passe | Non | Non | Natif (Encrypt / Protect) |
| Signatures numériques | Non | Non | Lecture / vérification / suppression ; la création n'a pas été trouvée lors de notre inspection |
Deux lignes nécessitent une mise en contexte honnête. Le filigrane n'apparaît pas dans la matrice car aucune des trois bibliothèques ne fournit d'API dédiée au filigrane — PowerPoint lui-même n'a pas de fonction de filigrane intégrée, et l'approche fonctionnelle (placer une forme, puis la remplir de texte ou d'une image) est disponible dans les trois bibliothèques. Les signatures numériques n'apparaissent que sous forme de lecture/vérification/suppression, car c'est ce que nous avons pu confirmer ; nous ne prétendons pas pouvoir les créer.
Remarquez comment les tableaux se lisent l'un par rapport à l'autre. Les capacités pour lesquelles python-pptx et power-pptx affichent « Non » sont précisément les types d'objets qui ont survécu intacts à notre test d'aller-retour. Ce qui manque n'est pas la sécurité — c'est la poignée pour faire le travail.
Le coût de la combler des lacunes
La préservation au niveau de l'octet ne rend pas une bibliothèque plus capable, et une API absente ne la rend pas destructrice. L'importance de la lacune dépend entièrement de ce que l'on demande à votre pipeline.
Si vos présentations sont construites à partir de modèles fixes et que Python ne fait que remplacer titres, chiffres et images — le fichier final animé étant renvoyé à PowerPoint pour la diffusion — python-pptx convient déjà, et ses API « manquantes » n'entrent jamais en jeu. Préservé mais non touché est exactement le comportement souhaité.
La lacune devient un coût réel lorsque l'exigence est de générer ou de transformer les fonctionnalités elles-mêmes : créer des animations pour des diapositives générées, réorganiser des jeux de diapositives par lots, construire des diagrammes SmartArt par programmation, ajouter des commentaires de révision depuis un système d'approbation, exporter des présentations finalisées en PDF ou en images sans Office de bureau, ou protéger les fichiers de sortie. Désormais, chaque « Non » de la matrice se convertit en l'un de ces contournements :
| Approche | Dépendance supplémentaire | Maintenance continue |
|---|---|---|
| Correctifs XML bruts sur le paquet | lxml, connaissance de la spécification OOXML | Chaque révision du format PowerPoint peut casser le XML de minutage ou de SmartArt écrit à la main |
| LibreOffice sans interface pour le rendu | LibreOffice plus Poppler ou PDFium | Dérive des versions, isolation des profils, différences de rendu par rapport à PowerPoint |
| Automatisation COM d'Office | Une installation d'Office de bureau sous licence | Windows uniquement, débit mono-instance, échecs COM sous charge |
| Un outil distinct pour chaque étape de conversion ou de protection | Une dépendance supplémentaire à chaque fois | Code de liaison, surfaces d'exception, transferts de fichiers |
Chacune de ces options est un choix d'ingénierie légitime, et des équipes les exploitent en production tous les jours. La question comptable est de savoir si vous voulez posséder cette pile — les correctifs XML, le conteneur LibreOffice, le pool de sessions COM — comme partie de votre produit, ou comme infrastructure autour de celui-ci. Un modèle mental utile : les bibliothèques open source déplacent la complexité dans votre code d'intégration, tandis qu'une bibliothèque commerciale la déplace dans une dépendance que vous licenciez.
Travailler avec une API de présentation plus complète
C'est ici que les exigences — et non le marketing — font entrer une bibliothèque commerciale en scène. Spire.Presentation for Python, la bibliothèque commerciale d'E-iceblue, expose les types d'objets que les paquets open source transportent mais ne modélisent pas : chronologies d'animation, transitions, SmartArt, commentaires, chiffrement et exports de rendu.
La différence se voit dans ce dont un pipeline cesse d'avoir besoin. Un flux de travail qui exigeait auparavant « python-pptx pour modifier, LibreOffice pour le rendu, un script COM pour ajouter des animations » peut se réduire à un seul modèle objet :
from spire.presentation import (
Presentation, FileFormat, AnimationEffectType, TransitionType,
)
from spire.presentation.common import PointF, DateTime
pres = Presentation()
pres.LoadFromFile("input.pptx")
# Move the slide at index 1 to index 3. The signature is Move(newIndex, oldIndex).
pres.Slides.Move(3, 1)
first = pres.Slides[0]
first.Timeline.MainSequence.AddEffect(first.Shapes[0], AnimationEffectType.Fade) # demo: choose your target shape
first.SlideShowTransition.Type = TransitionType.Fade
author = pres.CommentAuthors.AddAuthor("Reviewer", "RV")
first.AddComment(
author,
"Check the Q3 figures.",
PointF(100.0, 100.0), # PointF takes floats, not ints
DateTime.Parse("2026-11-23 10:00:00"), # DateTime has no Now(); parse a string
)
pres.SaveToFile("output.pdf", FileFormat.PDF)
pres.Encrypt("demo-password")
pres.SaveToFile("output.pptx", FileFormat.Pptx2013)
pres.Dispose()
Lors de notre exécution, PowerPoint a rouvert le fichier modifié avec 12 diapositives, trois séquences d'animation, deux commentaires et deux diapositives avec transition — exactement un de chaque ajouté au fichier d'origine. Le texte et l'auteur du nouveau commentaire étaient lisibles à la réouverture, et la transition en fondu était attachée à la première diapositive.
Le PDF et le PPTX chiffré sont des sorties distinctes : le PDF est exporté avant le chiffrement, tandis que le mot de passe ne s'applique qu'au PPTX enregistré ensuite.
La même famille d'API couvre les opérations voisines : fusionner plusieurs présentations en un seul jeu de diapositives, convertir PowerPoint en PDF dans le même processus qui modifie le fichier, et protéger le résultat par un mot de passe. Les objets signalés par notre matrice — animations, diagrammes SmartArt et commentaires — sont gérés par le même modèle objet.
Il ne s'agit pas de « l'open source échoue ». Les faits montrent le contraire : la voie open source gère bien une classe réelle et courante de travaux. La bibliothèque commerciale gagne sa place lorsque la liste des tâches elle-même s'élargit et que l'alternative consiste à maintenir plusieurs couches d'intégration autour d'une bibliothèque qui n'a jamais été conçue pour elles.
Considérations de déploiement et de licence
python-pptx, power-pptx et ps-python-pptx sont tous sous licence MIT. Le déploiement se fait par un pip install ; l'édition PPTX de base ne nécessite ni Microsoft Office ni processus de rendu externe. Le coût caché se situe ailleurs — dans les couches de contournement que vous construisez autour de la bibliothèque lorsqu'une exigence dépasse son API, comme décrit dans la section précédente.
Spire.Presentation est un logiciel commercial : l'utilisation professionnelle relève de ses conditions de licence commerciale. Les versions d'évaluation ajoutent un filigrane et peuvent limiter la sortie ; les mesures ci-dessus excluent donc le filigrane ; utilisez l'édition gratuite ou demandez une licence temporaire pour un test propre. Les conditions commerciales et les options de déploiement figurent sur la page de licence. Son environnement d'exécution apporte aussi des considérations de déploiement : vérifiez les plateformes prises en charge pour votre environnement cible (serveurs Linux, conteneurs, Windows) au regard des exigences actuelles du produit.
Choisir une approche pour votre projet
Plutôt qu'une liste de profils, voici un chemin de décision — chaque branche découle directement des faits ci-dessus :
- Vous générez ou modifiez du contenu de diapositive standard — texte, images, tableaux, graphiques, notes, liens hypertexte, vidéo — dans des modèles qui portent déjà vos animations et votre SmartArt. python-pptx suffit. Sa préservation en aller-retour est vérifiée, ses dépendances sont minimales et les API manquantes ne bloquent jamais ce travail. Si vous avez ensuite besoin de supprimer, réorganiser ou dupliquer des diapositives, ou de définir des transitions, évaluez power-pptx avec les mêmes tests.
- Vos diapositives doivent être créées, pas seulement remplies. Les animations, SmartArt et commentaires sont des sorties de votre pipeline, pas des artefacts d'un modèle. Évaluez une bibliothèque offrant ces API, ou prévoyez le budget pour les correctifs XML qui les remplacent.
- Le pipeline se termine dans un autre format ou dans un fichier verrouillé. Sortie PDF, images ou protégée par mot de passe sans installation d'Office de bureau. Évaluez une bibliothèque avec conversion et protection natives, ou planifiez explicitement l'outillage LibreOffice et de chiffrement.
Quel que soit votre choix, exécutez le même test sur vos propres présentations : ouvrir, enregistrer, compter les objets, comparer les rendus. Cela répond mieux que n'importe quel tableau de fonctionnalités. La page produit Spire.Presentation et son paquet de téléchargement sont des points de départ raisonnables si vous souhaitez ajouter Spire comme autre candidat ; si votre travail reste dans le modèle objet de python-pptx, le test vous le dira aussi.
Voir aussi
Elegir una biblioteca PPTX de Python para archivos reales de PowerPoint
Tabla de contenidos
- Qué contiene un archivo PPTX
- Resultados de la prueba de ida y vuelta
- Qué gestiona realmente python-pptx
- Proyecto original y bifurcaciones
- Comparación de cobertura de API
- El costo de cubrir esas brechas
- Una API de presentaciones más completa
- Consideraciones de implementación y licencias
- Elegir un enfoque para tu proyecto

Abre un archivo .pptx con una herramienta ZIP y encontrará mucho más que diapositivas: un gráfico respaldado por un libro de Excel incrustado, un diagrama de SmartArt dividido en cinco partes del paquete, XML de temporización de animaciones, definiciones de transición, notas del orador, comentarios modernos, un vídeo incrustado y relaciones de hipervínculo. Cualquier biblioteca PPTX de Python tiene que decidir qué hacer con todo eso, no solo con los cuadros de texto que ibas a editar.
La mayoría de las comparativas se detienen en las listas de funciones e insinúan que todo lo que no tiene una casilla de verificación se destruye al guardar. Pusimos a prueba esa suposición con un archivo de PowerPoint de 12 diapositivas que contenía esos objetos, lo ejecutamos con cada biblioteca y lo medimos a nivel de paquete, objeto y píxel.
El resultado separa dos preguntas. Preservación: python-pptx conserva lo que no puede tocar, lo que lo hace fiable para una amplia clase de trabajos de edición. Capacidad: la brecha aparece cuando un proyecto debe crear o manipular esos objetos. Este artículo presenta primero la evidencia y luego traza hasta dónde llega cada API.
Un archivo de PowerPoint es más que sus diapositivas visibles
Nuestro archivo de prueba se generó con el propio PowerPoint mediante automatización COM, no se armó a mano, por lo que proporciona un caso de prueba representativo con una variedad de objetos que se encuentran en presentaciones del mundo real. Tiene 12 diapositivas y 35 elementos de forma: una diapositiva de título, texto del cuerpo con un hipervínculo externo, una tabla de 4×3, un gráfico de columnas respaldado por un .xlsx incrustado, una imagen, una forma agrupada, un diagrama de SmartArt, dos formas animadas con una transición de Fundido, notas del orador, un comentario de revisión moderno, un vídeo incrustado y un enlace de salto interno de página.
Descomprimido, eso son 81 partes del paquete y unos 100 KB. La mayoría de esas partes son invisibles para el lector, pero sustentan la presentación: el XML de temporización de la diapositiva animada, el XML de transición, las cinco partes de SmartArt (datos, diseño, estilo rápido, colores y dibujo), la parte de comentario con metadatos del autor, el archivo multimedia del vídeo.

Esto importa para la selección de la biblioteca porque el formato OOXML no tiene un «modo seguro». Cuando una biblioteca abre un paquete, lo reescribe y lo guarda, cada una de esas partes está en juego. La pregunta nunca es solo «puede añadir un cuadro de texto». Es «qué hace con las 80 partes por las que no se le preguntó».
¿Qué ocurre cuando Python guarda un PPTX existente?
Abrimos el archivo con python-pptx 1.0.2, power-pptx 2.15.0 y Spire.Presentation for Python 11.8.1 (evaluación), lo guardamos sin ediciones y auditamos tres capas: la estructura del paquete ZIP, el modelo de objetos que el propio PowerPoint informa a través de COM y una comparación a nivel de píxel de las 12 diapositivas renderizadas por el mismo motor de PowerPoint a 1280×720. Spire.Presentation es un producto de E-iceblue, y esta prueba la realizó el editor; los resultados brutos se presentan a continuación, incluidos los casos en que los resultados son menos halagadores para Spire.
| Métrica | Original | python-pptx | power-pptx | Spire |
|---|---|---|---|---|
| Diapositivas | 12 | 12 | 12 | 12 |
| Formas | 35 † | 35 | 35 | 35 |
| Secuencias de animación | 2 | 2 | 2 | 2 |
| Diapositivas con una transición | 1 | 1 | 1 | 1 |
| Nodos de SmartArt | 5 | 5 | 5 | 5 |
| Comentarios | 1 | 1 | 1 | 1 |
| Vídeo / gráfico / tabla / notas | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 |
| Referencias de relación rotas | 0 | 0 | 0 | 0 |
| Diferencia de píxeles renderizados | — | 0,000% | 0,000% | 0,000% |
† Los elementos de forma se cuentan desde el XML de la diapositiva. Dos de ellos están dentro de un grupo, por lo que el recuento de formas de nivel superior de PowerPoint es 33 para cada archivo; la prueba de modificación a continuación informa 34 porque añadimos un cuadro de texto.
Dos detalles valen más que la tabla.
Primero, python-pptx y power-pptx no añadieron ni perdieron partes. Sus archivos eran aproximadamente un 7 % más pequeños porque la reserialización eliminó espacios en blanco y declaraciones de espacio de nombres repetidas; las partes de datos y diseño de SmartArt, la parte de comentario moderno y el XML de temporización de animaciones eran idénticos byte por byte. Eso es más fuerte que coincidir en los recuentos: las partes se conservaron, no se regeneraron.
Puedes reproducir esa primera capa en cualquier presentación:
import zipfile
before = zipfile.ZipFile("original.pptx")
after = zipfile.ZipFile("saved.pptx")
print(sorted(set(before.namelist()) ^ set(after.namelist()))) # [] = no parts added or lost
Una lista vacía es la comprobación inicial barata; si no está vacía, compara las partes diferentes antes de confiar en el archivo.

Segundo, la prueba de modificación. Editamos un título en la diapositiva 2, añadimos un cuadro de texto y guardamos. Las animaciones, la transición, SmartArt, el comentario, el vídeo, el gráfico y las notas seguían allí, y PowerPoint informó los mismos recuentos más una forma. Aquí es donde la afirmación común de que python-pptx elimina animaciones y SmartArt al guardar falla frente a la evidencia.
Un límite: verificamos que las definiciones y estructuras de animación sobrevivieron y que PowerPoint todavía las reconoce. No ejecutamos una presentación con diapositivas fotograma a fotograma, por lo que no afirmamos que las animaciones se reproduzcan exactamente como antes. Lo mismo se aplica al vídeo: los medios, las relaciones y el primer fotograma sobrevivieron; no se probó la reproducción en distintos dispositivos.

Spire preservó las funciones probadas a nivel de objeto y de renderizado, aunque se reescribieron algunas estructuras OOXML: el XML de temporización y de SmartArt se regeneró, el comentario moderno pasó al formato anterior comment1.xml + tag1.xml, y se añadieron nodos de temporización vacíos a cada diapositiva junto con elementos de transición. El autor y el texto del comentario se conservaron correctamente, pero no verificamos hilos de respuesta, estados resueltos ni metadatos de colaboración para un único comentario de prueba. PowerPoint reabrió el archivo con los objetos esperados; sin embargo, el diseño del paquete no se conservó byte por byte.
Qué gestiona realmente python-pptx
El resultado de ida y vuelta anterior explica por qué python-pptx sigue siendo la opción predeterminada para toda una familia de trabajos: edita bien los objetos que modela y preserva todo lo demás. Su modelo de objetos cubre el contenido estándar de una presentación de trabajo:
- Texto, imágenes, tablas, gráficos e hipervínculos: lectura y escritura para operaciones comunes, con cobertura que varía según el tipo de objeto; reemplazar los datos de un gráfico reescribe el libro de trabajo incrustado.
- Notas del orador: un objeto
NotesSlidede primera clase. - Vídeo:
add_movieinserta un objeto de vídeo. La API está marcada como experimental: tú especificas el tamaño, el tipo MIME y el fotograma de póster, y la compatibilidad de reproducción de medios es una cuestión aparte. - Diapositivas a partir de diseños:
add_slidecrea nuevas diapositivas a partir de los diseños del patrón, que es la base de la generación basada en plantillas.
Esa superficie de API admite el patrón de automatización más común: una plantilla corporativa fija, un script que crea diapositivas a partir de diseños predefinidos y rellena títulos, números, gráficos e imágenes por cliente o por semana, y un archivo final que vuelve a PowerPoint para su entrega. La fidelidad de ida y vuelta es exactamente lo que este patrón necesita, porque las animaciones y el SmartArt de la plantilla están pensados para preservarse, no para programarse.
from pptx import Presentation
prs = Presentation("template.pptx")
slide = prs.slides[1]
title = slide.shapes.title # works regardless of localized shape names
if title is not None:
title.text = "Q3 Review"
prs.save("edited.pptx")
Ejecútalo sobre una copia de tu plantilla y vuelve a abrir el resultado: el título cambia y el resto del archivo queda intacto.

La biblioteca tiene licencia MIT, no necesita una instalación de Office y solo incorpora un pequeño conjunto de dependencias: lxml, Pillow, XlsxWriter, typing-extensions, ninguna de las cuales requiere una aplicación de escritorio. Para los trabajos dentro de su modelo de objetos, es predecible y gratuita.
El ecosistema Python PPTX: proyecto original y bifurcaciones
El paquete original sigue en la versión 1.0.2, publicada en agosto de 2024, sin una versión formal más reciente desde entonces. Mientras tanto, varias bifurcaciones han introducido API y flujos de trabajo adicionales sobre el modelo de objetos original. Eso vale la pena entenderlo si estás eligiendo una alternativa a python-pptx, porque las opciones son menos «bibliotecas diferentes» y más «un mismo código base con conjuntos de funciones divergentes».
| Paquete | Versión | Posición |
|---|---|---|
| python-pptx | 1.0.2 | La base original, MIT |
| power-pptx | 2.15.0 | Una bifurcación mantenida activamente, MIT, Python 3.10–3.15 |
| ps-python-pptx | 1.3.0 | Una bifurcación que añade control de temas y fondos, asistentes para listas y texto enriquecido, texto alternativo, orden Z de formas y API para limpiar diapositivas |
| python-pptx-ng | 0.7.0 | Una rama histórica más antigua, en gran medida inactiva |
power-pptx mantiene el modelo de objetos original y añade gestión de diapositivas —remove, move, reorder, duplicate— además de set_transition para transiciones de diapositivas, un linter de diseños, reparación automática y una ruta de importación HTML. Su render_thumbnails renderiza diapositivas, pero a través de una cadena externa de LibreOffice y Poppler/PDFium en lugar de un motor integrado, lo que se convierte en una cuestión de implementación más que en una casilla de verificación de funciones.
Una trampa práctica que conviene conocer antes de experimentar: ps-python-pptx expone el mismo nombre de importación pptx que el paquete original. Instalar ambos en un mismo entorno no te dará los dos; usa entornos virtuales separados cuando quieras compararlos.
Dónde difieren las API
La tabla de ida y vuelta de la segunda sección responde a «qué sobrevive a un guardado». Esta tabla responde a una pregunta diferente: qué puede crear, leer y modificar activamente cada biblioteca. Mantén ambas separadas: en nuestra prueba, python-pptx preservó todos los tipos de objeto para los que no tiene API.
Creación de presentaciones
| Capacidad | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Texto, imágenes, tablas, gráficos, hipervínculos | Nativo | Nativo | Nativo |
| Notas del orador | Nativo | Nativo | Nativo |
| Inserción de vídeo | Experimental (add_movie); tamaño y fotograma de póster manuales |
Nativo | Nativo (InsertVideo) |
| Nuevas diapositivas | Nativo | Nativo | Nativo |
| Eliminar / reordenar / duplicar diapositivas | No | remove / move / reorder / duplicate |
Nativo |
| Animaciones de formas | No | No | Nativo (Timeline) |
| Transiciones de diapositivas | No | set_transition |
Nativo (SlideShowTransition) |
| Creación de SmartArt | No | No | Nativo (InsertSmartArt) |
| Comentarios | No | No | Nativo (AddComment / DeleteComment) |
Procesamiento de documentos
| Capacidad | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Abrir y editar un PPTX existente | Nativo | Nativo | Nativo |
| Exportación a PDF / imagen / SVG / HTML | No | render_thumbnails (entorno de ejecución externo) |
Nativo (PDF / imagen / SVG / HTML) |
| Combinar / dividir presentaciones | Copia manual de XML y relaciones | Asistentes duplicate; la combinación sigue siendo manual |
Nativo |
| Cifrado / protección con contraseña | No | No | Nativo (Encrypt / Protect) |
| Firmas digitales | No | No | Leer / verificar / eliminar; no se encontró la creación en nuestra inspección |
Dos filas necesitan un encuadre honesto. La marca de agua no aparece en la matriz porque ninguna de las tres incluye una API dedicada de marcas de agua; PowerPoint en sí no tiene una función de marca de agua integrada, y el enfoque práctico (colocar una forma y luego rellenarla con texto o una imagen) está disponible en las tres bibliotecas. Las firmas digitales aparecen solo como lectura/verificación/eliminación porque es lo que pudimos confirmar; no afirmamos la capacidad de crearlas.
Fíjate en cómo se leen las tablas entre sí. Las capacidades en las que python-pptx y power-pptx muestran «No» son precisamente los tipos de objeto que sobrevivieron intactos en nuestra prueba de ida y vuelta. Lo que falta no es seguridad: es el control para hacer el trabajo.
El costo de cubrir esas brechas
La preservación a nivel de byte no hace que una biblioteca sea más capaz, y una API ausente no la hace destructiva. Que la brecha importe depende enteramente de lo que se le pida hacer a tu canalización.
Si tus presentaciones se construyen a partir de plantillas fijas y Python solo intercambia títulos, números e imágenes —con el archivo final animado entregado de nuevo a PowerPoint para su entrega—, python-pptx ya encaja, y sus API «faltantes» nunca surgen. Preservado pero intacto es exactamente el comportamiento que deseas.
La brecha se convierte en un costo real cuando el requisito es generar o transformar las funciones en sí: crear animaciones para diapositivas generadas, reordenar presentaciones por lotes, construir SmartArt mediante programación, añadir comentarios de revisión desde un sistema de aprobación, exportar presentaciones terminadas a PDF o imágenes sin un Office de escritorio, o proteger los archivos de salida. Ahora cada «No» de la matriz se convierte en uno de estos rodeos:
| Enfoque | Dependencia adicional | Mantenimiento continuo |
|---|---|---|
| Parcheo directo del XML del paquete | lxml, conocimiento de la especificación OOXML | Cada revisión del formato de PowerPoint puede romper el XML de temporización o de SmartArt escrito a mano |
| LibreOffice en modo headless para renderizar | LibreOffice más Poppler o PDFium | Desviación de versiones, aislamiento de perfiles, diferencias de renderizado respecto a PowerPoint |
| Automatización COM de Office | Una instalación de Office de escritorio con licencia | Solo Windows, rendimiento de una sola instancia, fallos de COM bajo carga |
| Una herramienta separada por cada paso de conversión o protección | Una dependencia más por cada una | Código de pegamento, superficies de excepción, traspasos de archivos |
Cada una de estas es una elección de ingeniería legítima, y los equipos las usan en producción todos los días. La cuestión contable es si quieres asumir ese conjunto —los parches XML, el contenedor de LibreOffice, el grupo de sesiones COM— como parte de tu producto o como infraestructura a su alrededor. Un modelo mental útil: las bibliotecas de código abierto trasladan la complejidad a tu código de integración, mientras que una biblioteca comercial la traslada a una dependencia que licencias.
Trabajar con una API de presentaciones más completa
Este es el punto en que los requisitos —no el marketing— hacen entrar en escena a una biblioteca comercial. Spire.Presentation for Python, la biblioteca comercial de E-iceblue, expone los tipos de objeto que los paquetes de código abierto contienen pero no modelan: líneas de tiempo de animación, transiciones, SmartArt, comentarios, cifrado y exportaciones de renderizado.
La diferencia se nota en lo que una canalización deja de necesitar. Un flujo de trabajo que antes requería «python-pptx para editar, LibreOffice para renderizar, un script COM para añadir animaciones» puede reducirse a un único modelo de objetos:
from spire.presentation import (
Presentation, FileFormat, AnimationEffectType, TransitionType,
)
from spire.presentation.common import PointF, DateTime
pres = Presentation()
pres.LoadFromFile("input.pptx")
# Move the slide at index 1 to index 3. The signature is Move(newIndex, oldIndex).
pres.Slides.Move(3, 1)
first = pres.Slides[0]
first.Timeline.MainSequence.AddEffect(first.Shapes[0], AnimationEffectType.Fade) # demo: choose your target shape
first.SlideShowTransition.Type = TransitionType.Fade
author = pres.CommentAuthors.AddAuthor("Reviewer", "RV")
first.AddComment(
author,
"Check the Q3 figures.",
PointF(100.0, 100.0), # PointF takes floats, not ints
DateTime.Parse("2026-11-23 10:00:00"), # DateTime has no Now(); parse a string
)
pres.SaveToFile("output.pdf", FileFormat.PDF)
pres.Encrypt("demo-password")
pres.SaveToFile("output.pptx", FileFormat.Pptx2013)
pres.Dispose()
En nuestra ejecución, PowerPoint reabrió el archivo editado como 12 diapositivas con tres secuencias de animación, dos comentarios y dos diapositivas con transición: exactamente uno de cada uno añadido al archivo original. El texto y el autor del nuevo comentario eran legibles al reabrir, y la transición de Fundido se había asociado a la primera diapositiva.
El PDF y el PPTX cifrado son salidas separadas: el PDF se exporta antes del cifrado, mientras que la contraseña se aplica solo al PPTX que se guarda después.
La misma familia de API cubre las operaciones adyacentes: combinar varias presentaciones en una sola, convertir PowerPoint a PDF en el mismo proceso que edita el archivo y proteger el resultado con una contraseña. Los objetos que nuestra matriz señaló —animaciones, diagramas de SmartArt y comentarios— se gestionan con el mismo modelo de objetos.
Esto no es «el código abierto falla». La evidencia muestra lo contrario: la vía de código abierto maneja bien una clase de trabajo real y común. La biblioteca comercial se gana su lugar cuando la lista de tareas en sí se amplía, y la alternativa es mantener varias capas de integración alrededor de una biblioteca para la que nunca se diseñaron.
Consideraciones de implementación y licencias
python-pptx, power-pptx y ps-python-pptx tienen licencia MIT. La implementación es un pip install; la edición básica de PPTX no requiere Microsoft Office ni un proceso de renderizado externo. El costo oculto está en otro lugar: en las capas de solución alternativa que construyes alrededor de la biblioteca cuando un requisito supera su API, como se describe en la sección anterior.
Spire.Presentation es software comercial: el uso empresarial se rige por los términos de su licencia comercial. Las compilaciones de evaluación añaden una marca de agua y pueden limitar la salida, por lo que las mediciones anteriores excluyen la marca de agua; usa la edición gratuita o solicita una licencia temporal para una prueba limpia. Los términos comerciales y las opciones de implementación están en la página de licencias. Su entorno de ejecución también conlleva consideraciones de implementación: verifica las plataformas compatibles para tu entorno objetivo (servidores Linux, contenedores, Windows) frente a los requisitos actuales del producto.
Elegir un enfoque para tu proyecto
En lugar de una lista de perfiles, una ruta de decisión: cada rama se deriva directamente de la evidencia anterior:
- Generas o modificas contenido estándar de diapositivas —texto, imágenes, tablas, gráficos, notas, hipervínculos, vídeo— dentro de plantillas que ya incluyen tus animaciones y SmartArt. python-pptx es suficiente. Su preservación de ida y vuelta está verificada, sus dependencias son mínimas y las API faltantes nunca bloquean este trabajo. Si más adelante necesitas eliminar, reordenar o duplicar diapositivas, o establecer transiciones, evalúa power-pptx con las mismas pruebas.
- Tus diapositivas deben crearse, no solo rellenarse. Las animaciones, el SmartArt y los comentarios son salidas de tu canalización, no artefactos de una plantilla. Evalúa una biblioteca con esas API, o presupuesta el parcheo de XML que las reemplaza.
- La canalización termina en otro formato o en un archivo bloqueado. Salida en PDF, imágenes o protegida con contraseña sin una instalación de Office de escritorio. Evalúa una biblioteca con conversión y protección nativas, o planifica explícitamente las herramientas de LibreOffice y cifrado.
Elijas lo que elijas, ejecuta la misma prueba con tus propias presentaciones: abrir, guardar, contar objetos, comparar renderizaciones. Responde más que cualquier tabla de funciones. La página del producto Spire.Presentation y su paquete de descarga son puntos de partida razonables si quieres añadir Spire como otro candidato; si tu trabajo se mantiene dentro del modelo de objetos de python-pptx, la prueba también te lo dirá.
Véase también
Python-PPTX-Bibliothek für echte PowerPoint-Dateien auswählen
Inhaltsverzeichnis

Öffnen Sie eine .pptx-Datei mit einem ZIP-Tool, und Sie finden weit mehr als Folien: ein Diagramm, das auf einer eingebetteten Excel-Arbeitsmappe basiert, ein SmartArt-Diagramm, das über fünf Paketteile verteilt ist, Animations-Timing-XML, Übergangsdefinitionen, Notizen des Referenten, moderne Kommentare, ein eingebettetes Video und Hyperlink-Beziehungen. Jede Python-PPTX-Bibliothek muss entscheiden, was sie mit all dem macht – nicht nur mit den Textfeldern, die Sie bearbeiten wollten.
Die meisten Vergleiche enden bei Feature-Aufzählungen und legen nahe, dass alles ohne Häkchen beim Speichern zerstört wird. Wir haben diese Annahme mit einer 12-Folien-PowerPoint-Datei getestet, die diese Objekte enthielt, sie durch jede Bibliothek laufen lassen und auf Paket-, Objekt- und Pixelebene ausgewertet.
Das Ergebnis trennt zwei Fragen. Erhalt: python-pptx bewahrt, was es nicht anfassen kann, was es für eine große Klasse von Bearbeitungsaufgaben zuverlässig macht. Funktionsumfang: Die Lücke entsteht, wenn ein Projekt diese Objekte erstellen oder bearbeiten muss. Dieser Artikel präsentiert zuerst die Belege und ordnet dann ein, wo welche API reicht.
Eine PowerPoint-Datei ist mehr als ihre sichtbaren Folien
Unsere Testdatei wurde mit PowerPoint selbst über COM-Automatisierung erzeugt, nicht von Hand zusammengestellt, sodass sie eine repräsentative Testvorlage mit einer Reihe von Objekten aus realen Präsentationen bietet. Sie hat 12 Folien und 35 Shape-Elemente: eine Titelfolie, Fließtext mit einem externen Hyperlink, eine 4×3-Tabelle, ein Säulendiagramm mit einer eingebetteten .xlsx, ein Bild, eine gruppierte Form, ein SmartArt-Diagramm, zwei animierte Shapes mit einem Überblendungsübergang, Referentennotizen, einen modernen Überprüfungskommentar, ein eingebettetes Video und einen seiteninternen Sprunglink.
Entpackt sind das 81 Paketteile und etwa 100 KB. Die meisten dieser Teile sind für den Leser unsichtbar, aber tragend für die Präsentation: das Timing-XML für die animierte Folie, das Übergangs-XML, die fünf SmartArt-Teile (Daten, Layout, Schnellformat, Farben und Zeichnung), der Kommentarteil mit Autorenmetadaten, die Mediendatei für das Video.

Das ist für die Bibliotheksauswahl wichtig, weil das OOXML-Format keinen „sicheren Modus“ hat. Wenn eine Bibliothek ein Paket öffnet, es neu schreibt und speichert, ist jeder dieser Teile betroffen. Die Frage ist nie nur „Kann sie ein Textfeld hinzufügen?“, sondern „Was macht sie mit den 80 Teilen, nach denen niemand gefragt hat?“
Was passiert, wenn Python eine vorhandene PPTX speichert?
Wir haben die Datei mit python-pptx 1.0.2, power-pptx 2.15.0 und Spire.Presentation for Python 11.8.1 (Evaluierung) geöffnet, ohne Änderungen gespeichert und drei Ebenen geprüft: die ZIP-Paketstruktur, das Objektmodell, das PowerPoint selbst über COM meldet, und einen Pixelvergleich aller 12 Folien, die von derselben PowerPoint-Engine bei 1280×720 gerendert wurden. Spire.Presentation ist das eigene Produkt von E-iceblue, und dieser Test wurde vom Herausgeber durchgeführt; die Rohresultate werden unten wiedergegeben, einschließlich der Stellen, an denen die Ergebnisse für Spire weniger schmeichelhaft sind.
| Metrik | Original | python-pptx | power-pptx | Spire |
|---|---|---|---|---|
| Folien | 12 | 12 | 12 | 12 |
| Shapes | 35 † | 35 | 35 | 35 |
| Animationssequenzen | 2 | 2 | 2 | 2 |
| Folien mit einem Übergang | 1 | 1 | 1 | 1 |
| SmartArt-Knoten | 5 | 5 | 5 | 5 |
| Kommentare | 1 | 1 | 1 | 1 |
| Video / Diagramm / Tabelle / Notizen | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 |
| Defekte Beziehungsreferenzen | 0 | 0 | 0 | 0 |
| Gerenderte Pixeldifferenz | — | 0,000 % | 0,000 % | 0,000 % |
† Shape-Elemente werden aus dem Folien-XML gezählt. Zwei davon befinden sich in einer Gruppe, daher beträgt die Anzahl der übergeordneten Shapes in PowerPoint für jede Datei 33; der Änderungstest unten meldet 34, weil wir ein Textfeld hinzugefügt haben.
Zwei Details sind mehr wert als die Tabelle.
Erstens haben python-pptx und power-pptx keine Teile hinzugefügt oder verloren. Ihre Dateien waren etwa 7 % kleiner, weil die Neuserialisierung Leerraum und wiederholte Namespace-Deklarationen entfernte; die SmartArt-Daten- und -Layoutteile, der moderne Kommentarteil und das Animations-Timing-XML waren bytefürByte identisch. Das ist stärker als übereinstimmende Anzahlen: Die Teile wurden durchgereicht, nicht neu erzeugt.
Sie können diese erste Ebene bei jedem Deck reproduzieren:
import zipfile
before = zipfile.ZipFile("original.pptx")
after = zipfile.ZipFile("saved.pptx")
print(sorted(set(before.namelist()) ^ set(after.namelist()))) # [] = no parts added or lost
Eine leere Liste ist die günstige erste Prüfung; wenn sie nicht leer ist, vergleichen Sie die abweichenden Teile, bevor Sie der Datei vertrauen.

Zweitens der Änderungstest. Wir haben einen Titel auf Folie 2 bearbeitet, ein Textfeld hinzugefügt und gespeichert. Animationen, Übergang, SmartArt, Kommentar, Video, Diagramm und Notizen waren alle noch vorhanden, und PowerPoint meldete dieselben Anzahlen plus eine Form. Hier scheitert die verbreitete Behauptung, python-pptx verwerfe beim Speichern Animationen und SmartArt, an den Belegen.
Eine Einschränkung: Wir haben verifiziert, dass Animationsdefinitionen und -strukturen erhalten blieben und dass PowerPoint sie weiterhin erkennt. Wir haben keine Bildschirmpräsentation Bild für Bild ausgeführt, daher behaupten wir nicht, dass Animationen genau wie zuvor abgespielt werden. Dasselbe gilt für Video: Medien, Beziehungen und das erste Frame blieben erhalten; die Wiedergabe auf verschiedenen Geräten wurde nicht getestet.

Spire bewahrte die getesteten Features auf Objekt- und Rendering-Ebene, obwohl einige OOXML-Strukturen neu geschrieben wurden: Timing- und SmartArt-XML wurden neu erzeugt, der moderne Kommentar wurde zum älteren Format comment1.xml + tag1.xml, und jeder Folie wurden leere Timing-Knoten zusammen mit Übergangselementen hinzugefügt. Autor und Text des Kommentars kamen korrekt durch, aber wir haben Antwortthreads, gelöste Zustände oder Kollaborationsmetadaten für einen einzelnen Testkommentar nicht verifiziert. PowerPoint öffnete die Datei mit den erwarteten Objekten wieder; das Paketlayout blieb jedoch nicht bytegenau erhalten.
Was python-pptx tatsächlich abdeckt
Das obige Roundtrip-Ergebnis erklärt, warum python-pptx für eine ganze Familie von Aufgaben die Standardwahl bleibt: Es bearbeitet die Objekte, die es modelliert, gut und bewahrt alles andere. Sein Objektmodell deckt den Standardinhalt eines funktionierenden Decks ab:
- Text, Bilder, Tabellen, Diagramme und Hyperlinks – Lesen und Schreiben für gängige Operationen, wobei die Abdeckung je nach Objekttyp variiert; das Ersetzen von Diagrammdaten schreibt die eingebettete Arbeitsmappe neu.
- Referentennotizen – ein erstklassiges
NotesSlide-Objekt. - Video –
add_moviefügt ein Videoobjekt ein. Die API ist als experimentell gekennzeichnet: Sie geben Größe, MIME-Typ und Posterframe selbst an, und die Kompatibilität der Medienwiedergabe ist eine separate Frage. - Folien aus Layouts –
add_slideerstellt neue Folien aus den Layouts des Masters, was das Rückgrat der vorlagengetriebenen Generierung ist.
Diese API-Oberfläche unterstützt das gängigste Automatisierungsmuster: eine feste Unternehmensvorlage, ein Skript, das Folien aus vordefinierten Layouts erstellt und Titel, Zahlen, Diagramme und Bilder pro Kunde oder pro Woche einfügt, und eine endgültige Datei, die zur Auslieferung zurück in PowerPoint geht. Die Roundtrip-Treue ist genau das, was dieses Muster braucht, denn die Animationen und SmartArt der Vorlage sollen bewahrt, nicht geskriptet werden.
from pptx import Presentation
prs = Presentation("template.pptx")
slide = prs.slides[1]
title = slide.shapes.title # works regardless of localized shape names
if title is not None:
title.text = "Q3 Review"
prs.save("edited.pptx")
Führen Sie es gegen eine Kopie Ihrer Vorlage aus und öffnen Sie das Ergebnis erneut: Der Titel ändert sich, und der Rest der Datei bleibt unberührt.

Die Bibliothek ist MIT-lizenziert, benötigt keine Office-Installation und zieht nur wenige Abhängigkeiten ein – lxml, Pillow, XlsxWriter, typing-extensions –, von denen keine eine Desktop-Anwendung erfordert. Für Aufgaben innerhalb ihres Objektmodells ist sie vorhersehbar und kostenlos.
Das Python-PPTX-Ökosystem: Upstream und Forks
Das Upstream-Paket ist weiterhin bei Version 1.0.2, veröffentlicht im August 2024, mit keinem neueren formellen Release seitdem. In der Zwischenzeit haben mehrere Forks zusätzliche APIs und Workflows auf dem Upstream-Objektmodell eingeführt. Das ist wichtig zu verstehen, wenn Sie eine python-pptx-Alternative auswählen, denn die Optionen sind weniger „verschiedene Bibliotheken“ als vielmehr „eine Codebasis mit auseinanderlaufenden Funktionsumfängen“.
| Paket | Version | Position |
|---|---|---|
| python-pptx | 1.0.2 | Die Upstream-Basis, MIT |
| power-pptx | 2.15.0 | Ein aktiv gepflegter Fork, MIT, Python 3.10–3.15 |
| ps-python-pptx | 1.3.0 | Ein Fork, der Theme- und Hintergrundsteuerung, Listen- und Rich-Text-Hilfen, Alternativtext, Shape-Z-Reihenfolge und APIs zum Leeren von Folien hinzufügt |
| python-pptx-ng | 0.7.0 | Ein älterer historischer Zweig, weitgehend inaktiv |
power-pptx behält das Upstream-Objektmodell bei und ergänzt Folienverwaltung – remove, move, reorder, duplicate – sowie set_transition für Folienübergänge, einen Layout-Linter, automatische Reparatur und einen HTML-Importpfad. Seine render_thumbnails-Funktion rendert Folien, aber über eine externe LibreOffice- und Poppler/PDFium-Kette statt über eine integrierte Engine, was zu einer Bereitstellungsfrage statt zu einem Feature-Häkchen wird.
Eine praktische Falle, die Sie vor dem Experimentieren kennen sollten: ps-python-pptx stellt denselben Importnamen pptx bereit wie das Upstream-Paket. Beide in einer Umgebung zu installieren, liefert Ihnen nicht beide; verwenden Sie getrennte virtuelle Umgebungen, wenn Sie sie vergleichen möchten.
Wo sich die APIs unterscheiden
Die Roundtrip-Tabelle im zweiten Abschnitt beantwortet „Was überlebt ein Speichern“. Diese Tabelle beantwortet eine andere Frage: Was jede Bibliothek aktiv erstellen, lesen und ändern kann. Halten Sie beides getrennt – in unserem Test bewahrte python-pptx jeden Objekttyp, für den es keine API hat.
Präsentationserstellung
| Funktion | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Text, Bilder, Tabellen, Diagramme, Hyperlinks | Nativ | Nativ | Nativ |
| Referentennotizen | Nativ | Nativ | Nativ |
| Videoeinfügung | Experimentell (add_movie); manuelle Größenanpassung und Posterframe |
Nativ | Nativ (InsertVideo) |
| Neue Folien | Nativ | Nativ | Nativ |
| Folien löschen / neu anordnen / duplizieren | Nein | remove / move / reorder / duplicate |
Nativ |
| Shape-Animationen | Nein | Nein | Nativ (Timeline) |
| Folienübergänge | Nein | set_transition |
Nativ (SlideShowTransition) |
| SmartArt-Erstellung | Nein | Nein | Nativ (InsertSmartArt) |
| Kommentare | Nein | Nein | Nativ (AddComment / DeleteComment) |
Dokumentverarbeitung
| Funktion | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Eine vorhandene PPTX öffnen und bearbeiten | Nativ | Nativ | Nativ |
| PDF- / Bild- / SVG- / HTML-Export | Nein | render_thumbnails (externe Laufzeit) |
Nativ (PDF / Bild / SVG / HTML) |
| Präsentationen zusammenführen / aufteilen | Manuelles Kopieren von XML und Beziehungen | duplicate-Hilfen; Zusammenführen weiterhin manuell |
Nativ |
| Verschlüsselung / Kennwortschutz | Nein | Nein | Nativ (Encrypt / Protect) |
| Digitale Signaturen | Nein | Nein | Lesen / Prüfen / Entfernen; Erstellung in unserer Prüfung nicht gefunden |
Zwei Zeilen brauchen eine ehrliche Einordnung. Wasserzeichen erscheinen nicht in der Matrix, weil keines der drei Produkte eine dedizierte Wasserzeichen-API mitbringt – PowerPoint selbst hat keine integrierte Wasserzeichenfunktion, und der funktionierende Ansatz (eine Form platzieren und sie dann mit Text oder einem Bild füllen) ist in allen drei Bibliotheken verfügbar. Digitale Signaturen erscheinen nur als Lesen/Prüfen/Entfernen, weil das das ist, was wir bestätigen konnten; wir behaupten nicht, dass sie erstellt werden können.
Beachten Sie, wie die Tabellen im Verhältnis zueinander gelesen werden. Die Funktionen, bei denen python-pptx und power-pptx „Nein“ zeigen, sind genau die Objekttypen, die unseren Roundtrip-Test intakt überstanden. Was fehlt, ist nicht Sicherheit – es ist der Griff, um die Arbeit zu erledigen.
Die Kosten des Schließens dieser Lücken
Bytegenaue Bewahrung macht eine Bibliothek nicht leistungsfähiger, und eine fehlende API macht sie nicht destruktiv. Ob die Lücke wichtig ist, hängt ganz davon ab, was Ihre Pipeline leisten soll.
Wenn Ihre Präsentationen aus festen Vorlagen erstellt werden und Python nur Titel, Zahlen und Bilder austauscht – wobei die animierte endgültige Datei zur Auslieferung an PowerPoint zurückgeht –, passt python-pptx bereits, und seine „fehlenden“ APIs kommen nie zur Sprache. Bewahrt-aber-unberührt ist genau das Verhalten, das Sie wollen.
Die Lücke wird zu echten Kosten, wenn die Anforderung darin besteht, die Funktionen selbst zu generieren oder zu transformieren: Animationen für generierte Folien erstellen, Decks im Batch neu anordnen, SmartArt programmatisch aufbauen, Überprüfungskommentare aus einem Freigabesystem anhängen, fertige Decks ohne Desktop-Office nach PDF oder in Bilder exportieren oder Ausgabedateien schützen. Jetzt wird jedes „Nein“ in der Matrix zu einem dieser Workarounds:
| Ansatz | Zusätzliche Abhängigkeit | Laufende Wartung |
|---|---|---|
| Direktes XML-Patching am Paket | lxml, Kenntnisse der OOXML-Spezifikation | Jede PowerPoint-Formatüberarbeitung kann handgeschriebenes Timing- oder SmartArt-XML brechen |
| LibreOffice headless zum Rendern | LibreOffice plus Poppler oder PDFium | Versionsdrift, Profilisolierung, Rendering-Unterschiede zu PowerPoint |
| Office-COM-Automatisierung | Eine lizenzierte Desktop-Office-Installation | Nur Windows, Durchsatz mit einer Instanz, COM-Fehler unter Last |
| Ein separates Tool pro Konvertierungs- oder Schutzschritt | Jeweils eine weitere Abhängigkeit | Glue-Code, Ausnahmeflächen, Dateiübergaben |
Jede davon ist eine legitime technische Entscheidung, und Teams setzen sie täglich in der Produktion ein. Die Rechnungsfrage ist, ob Sie diesen Stack – die XML-Patches, den LibreOffice-Container, den COM-Sitzungspool – als Teil Ihres Produkts oder als Infrastruktur darum herum besitzen wollen. Ein nützliches Denkmodell: Die Open-Source-Bibliotheken verschieben die Komplexität in Ihren Integrationscode, während eine kommerzielle Bibliothek sie in eine Abhängigkeit verschiebt, die Sie lizenzieren.
Arbeiten mit einer vollständigeren Präsentations-API
An diesem Punkt bringen die Anforderungen – nicht das Marketing – eine kommerzielle Bibliothek ins Spiel. Spire.Presentation for Python, die eigene kommerzielle Bibliothek von E-iceblue, stellt die Objekttypen bereit, die die Open-Source-Pakete mitführen, aber nicht modellieren: Animationszeitleisten, Übergänge, SmartArt, Kommentare, Verschlüsselung und Rendering-Exporte.
Der Unterschied zeigt sich darin, was eine Pipeline nicht mehr braucht. Ein Workflow, der früher „python-pptx zum Bearbeiten, LibreOffice zum Rendern, ein COM-Skript zum Hinzufügen von Animationen“ erforderte, kann in einem einzigen Objektmodell zusammengefasst werden:
from spire.presentation import (
Presentation, FileFormat, AnimationEffectType, TransitionType,
)
from spire.presentation.common import PointF, DateTime
pres = Presentation()
pres.LoadFromFile("input.pptx")
# Move the slide at index 1 to index 3. The signature is Move(newIndex, oldIndex).
pres.Slides.Move(3, 1)
first = pres.Slides[0]
first.Timeline.MainSequence.AddEffect(first.Shapes[0], AnimationEffectType.Fade) # demo: choose your target shape
first.SlideShowTransition.Type = TransitionType.Fade
author = pres.CommentAuthors.AddAuthor("Reviewer", "RV")
first.AddComment(
author,
"Check the Q3 figures.",
PointF(100.0, 100.0), # PointF takes floats, not ints
DateTime.Parse("2026-11-23 10:00:00"), # DateTime has no Now(); parse a string
)
pres.SaveToFile("output.pdf", FileFormat.PDF)
pres.Encrypt("demo-password")
pres.SaveToFile("output.pptx", FileFormat.Pptx2013)
pres.Dispose()
In unserem Lauf öffnete PowerPoint die bearbeitete Datei wieder als 12 Folien mit drei Animationssequenzen, zwei Kommentaren und zwei Folien mit Übergang – genau je eines zusätzlich zur Originaldatei. Text und Autor des neuen Kommentars waren beim erneuten Öffnen lesbar, und der Überblendungsübergang war der ersten Folie zugeordnet.
Das PDF und die verschlüsselte PPTX sind separate Ausgaben: Das PDF wird vor der Verschlüsselung exportiert, während das Kennwort nur für die PPTX gilt, die danach gespeichert wird.
Dieselbe API-Familie deckt die angrenzenden Vorgänge ab: mehrere Präsentationen zu einem Deck zusammenführen, PowerPoint nach PDF konvertieren im selben Prozess, der die Datei bearbeitet, und das Ergebnis mit einem Kennwort schützen. Die Objekte, die unsere Matrix markierte – Animationen, SmartArt-Diagramme und Kommentare –, werden vom selben Objektmodell verarbeitet.
Das ist kein „Open Source versagt“. Die Belege zeigen das Gegenteil: Der Open-Source-Weg bewältigt eine reale und häufige Klasse von Arbeit gut. Die kommerzielle Bibliothek verdient ihren Platz, wenn die Aufgabenliste selbst breiter wird und die Alternative darin besteht, mehrere Integrationsschichten um eine Bibliothek herum zu pflegen, für die sie nie entworfen wurde.
Überlegungen zu Bereitstellung und Lizenzierung
python-pptx, power-pptx und ps-python-pptx sind alle MIT-lizenziert. Die Bereitstellung ist ein pip install; die Kernbearbeitung von PPTX erfordert weder Microsoft Office noch einen externen Rendering-Prozess. Die versteckten Kosten liegen woanders – in den Workaround-Schichten, die Sie um die Bibliothek herum aufbauen, wenn eine Anforderung ihre API übersteigt, wie im vorigen Abschnitt beschrieben.
Spire.Presentation ist kommerzielle Software: Die geschäftliche Nutzung fällt unter ihre kommerziellen Lizenzbedingungen. Evaluierungsbuilds fügen ein Wasserzeichen hinzu und können die Ausgabe begrenzen, daher schließen die obigen Messungen das Wasserzeichen aus; verwenden Sie die kostenlose Edition oder beantragen Sie eine temporäre Lizenz für einen sauberen Test. Kommerzielle Bedingungen und Bereitstellungsoptionen finden Sie auf der Lizenzierungsseite. Ihre Laufzeit bringt außerdem Bereitstellungsüberlegungen mit sich: Prüfen Sie die unterstützten Plattformen für Ihre Zielumgebung (Linux-Server, Container, Windows) anhand der aktuellen Anforderungen des Produkts.
Auswahl eines Ansatzes für Ihr Projekt
Statt einer Persona-Liste ein Entscheidungspfad – jeder Zweig folgt direkt aus den obigen Belegen:
- Sie generieren oder ändern standardmäßige Folieninhalte – Text, Bilder, Tabellen, Diagramme, Notizen, Hyperlinks, Video – in Vorlagen, die Ihre Animationen und SmartArt bereits enthalten. python-pptx ist ausreichend. Seine Roundtrip-Bewahrung ist verifiziert, seine Abhängigkeiten sind minimal, und die fehlenden APIs blockieren diese Arbeit nie. Wenn Sie später Folien löschen, neu anordnen oder duplizieren oder Übergänge festlegen müssen, evaluieren Sie power-pptx anhand derselben Tests.
- Ihre Folien müssen erstellt werden, nicht nur gefüllt. Animationen, SmartArt und Kommentare sind Ausgaben Ihrer Pipeline, nicht Artefakte einer Vorlage. Evaluieren Sie eine Bibliothek mit diesen APIs oder planen Sie das XML-Patching ein, das sie ersetzt.
- Die Pipeline endet in einem anderen Format oder einer gesperrten Datei. PDF, Bilder oder kennwortgeschützte Ausgabe ohne Desktop-Office-Installation. Evaluieren Sie eine Bibliothek mit nativer Konvertierung und Schutz oder planen Sie die LibreOffice- und Verschlüsselungstools ausdrücklich ein.
Was auch immer Sie wählen, führen Sie denselben Test mit Ihren eigenen Decks durch: öffnen, speichern, Objekte zählen, Renderings vergleichen. Er beantwortet mehr als jede Feature-Tabelle. Die Spire.Presentation-Produktseite und ihr Download-Paket sind sinnvolle Ausgangspunkte, wenn Sie Spire als weiteren Kandidaten hinzufügen möchten; wenn Ihre Arbeit innerhalb des Objektmodells von python-pptx bleibt, wird Ihnen der Test auch das sagen.
Siehe auch
- Ein PowerPoint-Dokument in Python erstellen
- PowerPoint in Python nach PDF konvertieren
- Animationen in PowerPoint hinzufügen oder extrahieren
- SmartArt in PowerPoint erstellen, lesen oder löschen
- PowerPoint-Präsentationen schützen oder den Schutz aufheben
- PowerPoint-Präsentationen in Python zusammenführen
Выбор библиотеки Python PPTX для реальных файлов PowerPoint
Содержание

Откройте файл .pptx с помощью ZIP-инструмента, и вы обнаружите гораздо больше, чем просто слайды: диаграмму, подкреплённую встроенной книгой Excel, диаграмму SmartArt, разделённую на пять частей пакета, XML-тайминги анимации, определения переходов, заметки докладчика, современные комментарии, встроенное видео и связи гиперссылок. Любая библиотека Python для PPTX должна решить, что делать со всем этим, а не только с текстовыми блоками, которые вы пришли редактировать.
Большинство сравнений ограничиваются списками функций и подразумевают, что всё, что не отмечено галочкой, уничтожается при сохранении. Мы проверили это предположение на файле PowerPoint из 12 слайдов, содержащем эти объекты, прогнав его через каждую библиотеку и измерив на уровне пакета, объектов и пикселей.
Результат разделяет два вопроса. Сохранность: python-pptx сохраняет то, что не может изменить, что делает его надёжным для большого класса задач редактирования. Возможности: разрыв открывается, когда проект должен создавать или манипулировать этими объектами. В этой статье сначала представлены доказательства, а затем показано, где простирается каждый API.
Файл PowerPoint — это больше, чем его видимые слайды
Наш тестовый файл был создан самим PowerPoint через COM-автоматизацию, а не собран вручную, поэтому он представляет собой репрезентативный тестовый образец с диапазоном объектов, встречающихся в реальных презентациях. В нём 12 слайдов и 35 элементов фигур: титульный слайд, основной текст с внешней гиперссылкой, таблица 4×3, столбчатая диаграмма, подкреплённая встроенным файлом .xlsx, изображение, сгруппированная фигура, диаграмма SmartArt, две анимированные фигуры с переходом Fade, заметки докладчика, современный комментарий проверки, встроенное видео и внутренняя ссылка-переход на страницу.
В распакованном виде это 81 часть пакета и около 100 КБ. Большинство этих частей невидимы для читателя, но несут нагрузку для презентации: XML-тайминги для анимированного слайда, XML-перехода, пять частей SmartArt (данные, макет, быстрый стиль, цвета и рисунок), часть комментария с метаданными автора, медиафайл для видео.

Это важно для выбора библиотеки, потому что формат OOXML не имеет «безопасного режима». Когда библиотека открывает пакет, перезаписывает его и сохраняет, каждая из этих частей оказывается в области действия. Вопрос никогда не сводится только к «может ли она добавить текстовый блок». Он звучит так: «что она делает с 80 частями, о которых её не просили».
Что происходит, когда Python сохраняет существующий PPTX?
Мы открыли файл с помощью python-pptx 1.0.2, power-pptx 2.15.0 и Spire.Presentation for Python 11.8.1 (оценочная версия), сохранили без изменений и проверили три уровня: структуру ZIP-пакета, объектную модель, которую сам PowerPoint сообщает через COM, и попиксельное сравнение всех 12 слайдов, отрисованных тем же движком PowerPoint при 1280×720. Spire.Presentation — собственный продукт E-iceblue, и этот тест проводился издателем; необработанные результаты приведены ниже, включая те места, где результаты менее лестны для Spire.
| Показатель | Оригинал | python-pptx | power-pptx | Spire |
|---|---|---|---|---|
| Слайды | 12 | 12 | 12 | 12 |
| Фигуры | 35 † | 35 | 35 | 35 |
| Последовательности анимации | 2 | 2 | 2 | 2 |
| Слайды с переходом | 1 | 1 | 1 | 1 |
| Узлы SmartArt | 5 | 5 | 5 | 5 |
| Комментарии | 1 | 1 | 1 | 1 |
| Видео / диаграмма / таблица / заметки | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 |
| Нарушенные ссылки связей | 0 | 0 | 0 | 0 |
| Разница отрисованных пикселей | — | 0.000% | 0.000% | 0.000% |
† Элементы фигур подсчитаны по XML слайда. Два из них находятся внутри группы, поэтому верхнеуровневое количество фигур PowerPoint равно 33 для каждого файла; тест модификации ниже сообщает 34, потому что мы добавили один текстовый блок.
Две детали стоят больше, чем вся таблица.
Во-первых, python-pptx и power-pptx не добавили и не потеряли ни одной части. Их файлы были примерно на 7% меньше, потому что повторная сериализация удалила пробелы и повторяющиеся объявления пространств имён; части данных и макета SmartArt, часть современного комментария и XML-тайминги анимации были побайтово идентичны. Это сильнее, чем совпадение количеств: части были перенесены, а не сгенерированы заново.
Вы можете воспроизвести этот первый уровень на любой колоде:
import zipfile
before = zipfile.ZipFile("original.pptx")
after = zipfile.ZipFile("saved.pptx")
print(sorted(set(before.namelist()) ^ set(after.namelist()))) # [] = no parts added or lost
Пустой список — это дешёвая первая проверка; если он не пуст, сравните отличающиеся части, прежде чем доверять файлу.

Во-вторых, тест модификации. Мы отредактировали заголовок на слайде 2, добавили текстовый блок и сохранили. Анимации, переход, SmartArt, комментарий, видео, диаграмма и заметки всё ещё были на месте, и PowerPoint сообщил те же количества плюс одна фигура. Именно здесь распространённое утверждение, что python-pptx удаляет анимации и SmartArt при сохранении, не выдерживает проверки доказательствами.
Одна граница: мы проверили, что определения и структуры анимации сохранились и что PowerPoint по-прежнему их распознаёт. Мы не запускали показ слайдов покадрово, поэтому не утверждаем, что анимации воспроизводятся в точности как раньше. То же самое относится к видео: медиа, связи и первый кадр сохранились; воспроизведение на разных устройствах не тестировалось.

Spire сохранил протестированные функции на уровне объектов и рендеринга, хотя некоторые структуры OOXML были перезаписаны: XML-тайминги и SmartArt были перегенерированы, современный комментарий стал старым форматом comment1.xml + tag1.xml, а на каждый слайд были добавлены пустые узлы таймингов вместе с элементами переходов. Автор и текст комментария передались корректно, но мы не проверяли цепочки ответов, состояния решённости или метаданные совместной работы для единственного тестового комментария. PowerPoint повторно открыл файл с ожидаемыми объектами; однако структура пакета не была сохранена побайтово.
Что на самом деле поддерживает python-pptx
Результат кругового сохранения выше объясняет, почему python-pptx остаётся выбором по умолчанию для целого семейства задач: он хорошо редактирует моделируемые им объекты и сохраняет всё остальное. Его объектная модель охватывает стандартное содержимое рабочей колоды:
- Текст, изображения, таблицы, диаграммы и гиперссылки — чтение и запись для распространённых операций, с покрытием, варьирующимся по типу объекта; замена данных диаграммы перезаписывает встроенную книгу.
- Заметки докладчика — полноценный объект
NotesSlide. - Видео —
add_movieвставляет объект видео. API помечен как экспериментальный: размер, MIME-тип и постер-кадр вы указываете сами, а совместимость воспроизведения медиа — отдельный вопрос. - Слайды из макетов —
add_slideсоздаёт новые слайды из макетов мастер-слайда, что является основой для генерации на основе шаблонов.
Эта поверхность API поддерживает самый распространённый шаблон автоматизации: фиксированный корпоративный шаблон, скрипт, который создаёт слайды из предопределённых макетов и заполняет заголовки, числа, диаграммы и изображения для каждого клиента или каждую неделю, и итоговый файл, который возвращается в PowerPoint для доставки. Точность кругового сохранения — именно то, что нужно этому шаблону, потому что анимации и SmartArt шаблона должны сохраняться, а не задаваться скриптом.
from pptx import Presentation
prs = Presentation("template.pptx")
slide = prs.slides[1]
title = slide.shapes.title # works regardless of localized shape names
if title is not None:
title.text = "Q3 Review"
prs.save("edited.pptx")
Запустите его на копии вашего шаблона и откройте результат заново: заголовок меняется, а остальная часть файла остаётся нетронутой.

Библиотека распространяется под лицензией MIT, не требует установки Office и подтягивает небольшой набор зависимостей — lxml, Pillow, XlsxWriter, typing-extensions — ни одна из которых не требует настольного приложения. Для задач внутри её объектной модели она предсказуема и бесплатна.
Экосистема Python PPTX: оригинальный проект и форки
Оригинальный пакет остаётся на версии 1.0.2, выпущенной в августе 2024 года, без более новых официальных релизов с тех пор. Тем временем несколько форков добавили дополнительные API и рабочие процессы поверх оригинальной объектной модели. Это стоит понимать, если вы выбираете альтернативу python-pptx, потому что варианты — это не столько «разные библиотеки», сколько «одна кодовая база с расходящимися наборами функций».
| Пакет | Версия | Позиция |
|---|---|---|
| python-pptx | 1.0.2 | Оригинальная база, MIT |
| power-pptx | 2.15.0 | Активно поддерживаемый форк, MIT, Python 3.10–3.15 |
| ps-python-pptx | 1.3.0 | Форк, добавляющий управление темой и фоном, помощники для списков и форматированного текста, альтернативный текст, порядок наложения фигур и API очистки слайдов |
| python-pptx-ng | 0.7.0 | Более старая историческая ветка, в основном неактивная |
power-pptx сохраняет оригинальную объектную модель и добавляет управление слайдами — remove, move, reorder, duplicate — плюс set_transition для переходов слайдов, линтер макетов, автоматическое восстановление и путь импорта HTML. Его render_thumbnails отрисовывает слайды, но через внешнюю цепочку LibreOffice и Poppler/PDFium, а не через встроенный движок, что становится вопросом развёртывания, а не пунктом в списке функций.
Одна практическая ловушка, которую стоит знать перед экспериментами: ps-python-pptx использует то же имя импорта pptx, что и оригинальный пакет. Установка обоих в одном окружении не даст вам оба; используйте отдельные виртуальные окружения, когда хотите их сравнить.
Где API различаются
Таблица кругового сохранения во втором разделе отвечает на вопрос «что переживает сохранение». Эта таблица отвечает на другой вопрос: что каждая библиотека может активно создавать, читать и изменять. Держите их раздельно — в нашем тесте python-pptx сохранил каждый тип объекта, для которого у него нет API.
Создание презентаций
| Возможность | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Текст, изображения, таблицы, диаграммы, гиперссылки | Нативно | Нативно | Нативно |
| Заметки докладчика | Нативно | Нативно | Нативно |
| Вставка видео | Экспериментально (add_movie); ручной размер и постер-кадр |
Нативно | Нативно (InsertVideo) |
| Новые слайды | Нативно | Нативно | Нативно |
| Удаление / переупорядочивание / дублирование слайдов | Нет | remove / move / reorder / duplicate |
Нативно |
| Анимации фигур | Нет | Нет | Нативно (Timeline) |
| Переходы слайдов | Нет | set_transition |
Нативно (SlideShowTransition) |
| Создание SmartArt | Нет | Нет | Нативно (InsertSmartArt) |
| Комментарии | Нет | Нет | Нативно (AddComment / DeleteComment) |
Обработка документов
| Возможность | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Открытие и редактирование существующего PPTX | Нативно | Нативно | Нативно |
| Экспорт в PDF / изображения / SVG / HTML | Нет | render_thumbnails (внешняя среда выполнения) |
Нативно (PDF / изображения / SVG / HTML) |
| Объединение / разделение презентаций | Ручное копирование XML и связей | Помощники duplicate; объединение по-прежнему вручную |
Нативно |
| Шифрование / защита паролем | Нет | Нет | Нативно (Encrypt / Protect) |
| Цифровые подписи | Нет | Нет | Чтение / проверка / удаление; создание в нашей проверке не обнаружено |
Две строки требуют честной формулировки. Нанесение водяных знаков не появляется в матрице, потому что ни одна из трёх библиотек не поставляет выделенный API для водяных знаков — в самом PowerPoint нет встроенной функции водяных знаков, а рабочий подход (размещение фигуры, затем заполнение её текстом или изображением) доступен во всех трёх библиотеках. Цифровые подписи появляются только как чтение/проверка/удаление, потому что это то, что мы смогли подтвердить; мы не заявляем о возможности их создания.
Обратите внимание, как таблицы соотносятся друг с другом. Возможности, где python-pptx и power-pptx показывают «Нет», — это именно те типы объектов, которые сохранились нетронутыми в нашем тесте кругового сохранения. Не хватает не безопасности — не хватает ручки для выполнения работы.
Цена закрытия этих пробелов
Побайтовое сохранение не делает библиотеку более функциональной, а отсутствующий API не делает её разрушительной. Имеет ли пробел значение, полностью зависит от того, что требуется от вашего конвейера.
Если ваши презентации строятся из фиксированных шаблонов, и Python только подменяет заголовки, числа и изображения — а анимированный итоговый файл передаётся обратно в PowerPoint для доставки — python-pptx уже подходит, и его «отсутствующие» API никогда не всплывают. Сохранено-но-нетронуто — это именно то поведение, которое вам нужно.
Пробел становится реальной ценой, когда требование состоит в том, чтобы генерировать или преобразовывать сами функции: создание анимаций для сгенерированных слайдов, пакетное переупорядочивание колод, программное построение SmartArt, добавление комментариев проверки из системы утверждения, экспорт готовых колод в PDF или изображения без настольного Office или защита выходных файлов. Теперь каждое «Нет» в матрице превращается в один из этих обходных путей:
| Подход | Дополнительная зависимость | Постоянное сопровождение |
|---|---|---|
| Прямое патчинг XML в пакете | lxml, знание спецификации OOXML | Каждая редакция формата PowerPoint может сломать написанный вручную XML таймингов или SmartArt |
| LibreOffice headless для рендеринга | LibreOffice плюс Poppler или PDFium | Дрейф версий, изоляция профилей, отличия рендеринга от PowerPoint |
| Автоматизация Office COM | Лицензионная установка настольного Office | Только Windows, пропускная способность в одном экземпляре, сбои COM под нагрузкой |
| Отдельный инструмент для каждого шага преобразования или защиты | Ещё одна зависимость для каждого | Связующий код, поверхности исключений, передача файлов |
Каждый из них — законный инженерный выбор, и команды используют их в продакшене каждый день. Вопрос учёта — хотите ли вы владеть этим стеком — XML-патчами, контейнером LibreOffice, пулом COM-сессий — как частью вашего продукта или как инфраструктурой вокруг него. Полезная мысленная модель: библиотеки с открытым исходным кодом переносят сложность в ваш код интеграции, а коммерческая библиотека переносит её в зависимость, которую вы лицензируете.
Работа с более полным API для презентаций
Это тот момент, когда требования — а не маркетинг — выводят коммерческую библиотеку на сцену. Spire.Presentation for Python, собственная коммерческая библиотека E-iceblue, предоставляет типы объектов, которые пакеты с открытым исходным кодом содержат, но не моделируют: таймлайны анимации, переходы, SmartArt, комментарии, шифрование и экспорт рендеринга.
Разница проявляется в том, что конвейеру больше не нужно. Рабочий процесс, который раньше требовал «python-pptx для редактирования, LibreOffice для рендеринга, COM-скрипт для добавления анимаций», может свернуться в единую объектную модель:
from spire.presentation import (
Presentation, FileFormat, AnimationEffectType, TransitionType,
)
from spire.presentation.common import PointF, DateTime
pres = Presentation()
pres.LoadFromFile("input.pptx")
# Move the slide at index 1 to index 3. The signature is Move(newIndex, oldIndex).
pres.Slides.Move(3, 1)
first = pres.Slides[0]
first.Timeline.MainSequence.AddEffect(first.Shapes[0], AnimationEffectType.Fade) # demo: choose your target shape
first.SlideShowTransition.Type = TransitionType.Fade
author = pres.CommentAuthors.AddAuthor("Reviewer", "RV")
first.AddComment(
author,
"Check the Q3 figures.",
PointF(100.0, 100.0), # PointF takes floats, not ints
DateTime.Parse("2026-11-23 10:00:00"), # DateTime has no Now(); parse a string
)
pres.SaveToFile("output.pdf", FileFormat.PDF)
pres.Encrypt("demo-password")
pres.SaveToFile("output.pptx", FileFormat.Pptx2013)
pres.Dispose()
В нашем запуске PowerPoint повторно открыл отредактированный файл с 12 слайдами, тремя последовательностями анимации, двумя комментариями и двумя слайдами с переходами — ровно по одному каждого типа добавлено к оригинальному файлу. Текст и автор нового комментария читались при повторном открытии, а переход Fade был привязан к первому слайду.
PDF и зашифрованный PPTX — это отдельные выходные данные: PDF экспортируется до шифрования, а пароль применяется только к PPTX, который сохраняется после.
Это же семейство API охватывает смежные операции: объединение нескольких презентаций в одну колоду, преобразование PowerPoint в PDF в том же процессе, что редактирует файл, и защита результата паролем. Объекты, которые мы отметили в матрице — анимации, диаграммы SmartArt и комментарии — обрабатываются той же объектной моделью.
Это не «открытый исходный код не работает». Доказательства показывают обратное: путь с открытым исходным кодом хорошо справляется с реальным и распространённым классом работы. Коммерческая библиотека заслуживает своё место, когда сам список задач расширяется, а альтернативой является поддержка нескольких слоёв интеграции вокруг библиотеки, которая никогда для них не предназначалась.
Развёртывание и лицензирование
python-pptx, power-pptx и ps-python-pptx распространяются под лицензией MIT. Развёртывание — это pip install; для базового редактирования PPTX не требуется Microsoft Office или внешний процесс рендеринга. Скрытая стоимость лежит в другом месте — в слоях обходных путей, которые вы строите вокруг библиотеки, когда требование превышает её API, как описано в предыдущем разделе.
Spire.Presentation — коммерческое программное обеспечение: коммерческое использование подпадает под условия его коммерческой лицензии. Оценочные сборки добавляют водяной знак и могут ограничивать вывод, поэтому приведённые выше измерения исключают водяной знак; используйте бесплатную версию или подайте заявку на временную лицензию для чистого теста. Коммерческие условия и варианты развёртывания находятся на странице лицензирования. Её среда выполнения также приносит соображения по развёртыванию: проверьте поддерживаемые платформы для вашей целевой среды (серверы Linux, контейнеры, Windows) на соответствие текущим требованиям продукта.
Выбор подхода для вашего проекта
Вместо списка персон — путь принятия решения, каждая ветвь которого напрямую следует из доказательств выше:
- Вы генерируете или изменяете стандартное содержимое слайдов — текст, изображения, таблицы, диаграммы, заметки, гиперссылки, видео — внутри шаблонов, которые уже несут ваши анимации и SmartArt. python-pptx достаточно. Его сохранность при круговом сохранении проверена, его зависимости минимальны, а отсутствующие API никогда не блокируют эту работу. Если позже вам понадобится удалять, переупорядочивать или дублировать слайды или задавать переходы, оцените power-pptx на тех же тестах.
- Ваши слайды должны создаваться, а не просто заполняться. Анимации, SmartArt и комментарии — это результаты вашего конвейера, а не артефакты шаблона. Оцените библиотеку с такими API или заложите бюджет на патчинг XML, который их заменяет.
- Конвейер заканчивается в другом формате или заблокированном файле. PDF, изображения или защищённый паролем вывод без установки настольного Office. Оцените библиотеку с нативным преобразованием и защитой или спланируйте инструментарий LibreOffice и шифрования явно.
Что бы вы ни выбрали, проведите тот же тест на ваших собственных колодах: откройте, сохраните, подсчитайте объекты, сравните рендеринг. Это даёт больше ответов, чем любая таблица функций. Страница продукта Spire.Presentation и его загружаемый пакет — разумные отправные точки, если вы хотите добавить Spire в качестве ещё одного кандидата; если ваша работа остаётся внутри объектной модели python-pptx, тест скажет вам и это.
См. также
Choosing a Python PPTX Library for Real PowerPoint Files

Open a .pptx file with a ZIP tool and you will find far more than slides: a chart backed by an embedded Excel workbook, a SmartArt diagram split across five package parts, animation timing XML, transition definitions, speaker notes, modern comments, an embedded video, and hyperlink relationships. Any Python PPTX library has to decide what to do with all of that, not just the text boxes you came to edit.
Most comparisons stop at feature bullets and imply that anything without a checkbox is destroyed on save. We tested that assumption with a 12-slide PowerPoint file containing those objects, run through each library and measured at the package, object, and pixel level.
The result separates two questions. Preservation: python-pptx keeps what it cannot touch, which makes it dependable for a large class of editing jobs. Capability: the gap opens when a project must create or manipulate those objects. This article presents the evidence first, then maps where each API reaches.
A PowerPoint File Is More Than Its Visible Slides
Our test file was generated with PowerPoint itself through COM automation, not assembled by hand, so it provides a representative test fixture with a range of objects found in real-world presentations. It has 12 slides and 35 shape elements: a title slide, body text with an external hyperlink, a 4×3 table, a column chart backed by an embedded .xlsx, an image, a grouped shape, a SmartArt diagram, two animated shapes with a Fade transition, speaker notes, a modern review comment, an embedded video, and a page-internal jump link.
Unzipped, that is 81 package parts and about 100 KB. Most of those parts are invisible to the reader but load-bearing for the presentation: the timing XML for the animated slide, the transition XML, the five SmartArt parts (data, layout, quick style, colors, and drawing), the comment part with author metadata, the media file for the video.

This matters for library selection because the OOXML format does not have a "safe mode." When a library opens a package, rewrites it, and saves it, every one of those parts is in scope. The question is never only "can it add a text box." It is "what does it do to the 80 parts it was not asked about."
What Happens When Python Saves an Existing PPTX?
We opened the file with python-pptx 1.0.2, power-pptx 2.15.0, and Spire.Presentation for Python 11.8.1 (evaluation), saved without edits, and audited three layers: the ZIP package structure, the object model that PowerPoint itself reports through COM, and a pixel-level diff of all 12 slides rendered by the same PowerPoint engine at 1280×720. Spire.Presentation is E-iceblue's own product, and this test was run by the publisher; the raw results are reported below, including where the results are less flattering to Spire.
| Metric | Original | python-pptx | power-pptx | Spire |
|---|---|---|---|---|
| Slides | 12 | 12 | 12 | 12 |
| Shapes | 35 † | 35 | 35 | 35 |
| Animation sequences | 2 | 2 | 2 | 2 |
| Slides with a transition | 1 | 1 | 1 | 1 |
| SmartArt nodes | 5 | 5 | 5 | 5 |
| Comments | 1 | 1 | 1 | 1 |
| Video / chart / table / notes | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 | 1/1/1/1 |
| Broken relationship references | 0 | 0 | 0 | 0 |
| Rendered pixel difference | — | 0.000% | 0.000% | 0.000% |
† Shape elements are counted from the slide XML. Two of them sit inside a group, so PowerPoint's top-level shape count is 33 for every file; the modification test below reports 34 because we added one text box.
Two details are worth more than the table.
First, python-pptx and power-pptx added and lost no parts. Their files were about 7% smaller because re-serialization dropped whitespace and repeated namespace declarations; the SmartArt data and layout parts, the modern comment part, and the animation timing XML were byte-for-byte identical. That is stronger than matching counts: the parts were carried through, not regenerated.
You can reproduce that first layer on any deck:
import zipfile
before = zipfile.ZipFile("original.pptx")
after = zipfile.ZipFile("saved.pptx")
print(sorted(set(before.namelist()) ^ set(after.namelist()))) # [] = no parts added or lost
An empty list is the cheap first check; if it is not empty, compare the differing parts before trusting the file.

Second, the modification test. We edited a title on slide 2, added a text box, and saved. Animations, transition, SmartArt, comment, video, chart, and notes were all still there, and PowerPoint reported the same counts plus one shape. This is where the common claim that python-pptx drops animations and SmartArt on save fails against evidence.
One boundary: we verified that animation definitions and structures survived and that PowerPoint still recognizes them. We did not run a slideshow frame by frame, so we do not claim animations play exactly as before. The same applies to video: media, relationships, and the first frame survived; playback across devices was not tested.

Spire preserved the tested features at the object and rendering levels, though some OOXML structures were rewritten: timing and SmartArt XML were regenerated, the modern comment became the older comment1.xml + tag1.xml format, and empty timing nodes were added to every slide along with transition elements. The comment's author and text came through correctly, but we did not verify reply threads, resolved states, or collaboration metadata for a single test comment. PowerPoint reopened the file with the expected objects; the package layout, however, was not preserved byte for byte.
What python-pptx Actually Handles
The round-trip result above explains why python-pptx remains the default choice for a whole family of jobs: it edits the objects it models well and preserves everything else. Its object model covers the standard content of a working deck:
- Text, images, tables, charts, and hyperlinks — read and write for common operations, with coverage varying by object type; replacing chart data rewrites the embedded workbook.
- Speaker notes — a first-class
NotesSlideobject. - Video —
add_movieinserts a video object. The API is marked experimental: you specify the size, MIME type, and poster frame yourself, and media playback compatibility is a separate question. - Slides from layouts —
add_slidebuilds new slides from the master's layouts, which is the backbone of template-driven generation.
That API surface supports the most common automation pattern: a fixed corporate template, a script that creates slides from predefined layouts and fills in titles, numbers, charts, and images per customer or per week, and a final file that goes back into PowerPoint for delivery. Round-trip fidelity is exactly what this pattern needs, because the template's animations and SmartArt are meant to be preserved, not scripted.
from pptx import Presentation
prs = Presentation("template.pptx")
slide = prs.slides[1]
title = slide.shapes.title # works regardless of localized shape names
if title is not None:
title.text = "Q3 Review"
prs.save("edited.pptx")
Run it against a copy of your template and reopen the result: the title changes, and the rest of the file is untouched.

The library is MIT-licensed, needs no Office installation, and pulls in a small dependency set — lxml, Pillow, XlsxWriter, typing-extensions — none of which requires a desktop application. For jobs inside its object model, it is predictable and free.
The Python PPTX Ecosystem: Upstream and Forks
The upstream package remains at version 1.0.2, released in August 2024, with no newer formal release since. Meanwhile, several forks have introduced additional APIs and workflows on top of the upstream object model. That is worth understanding if you are picking a python-pptx alternative, because the options are less "different libraries" and more "one codebase with diverging feature sets."
| Package | Version | Position |
|---|---|---|
| python-pptx | 1.0.2 | The upstream base, MIT |
| power-pptx | 2.15.0 | An actively maintained fork, MIT, Python 3.10–3.15 |
| ps-python-pptx | 1.3.0 | A fork adding theme and background control, list and rich-text helpers, alt text, shape z-order, and slide-clearing APIs |
| python-pptx-ng | 0.7.0 | An older historical branch, largely inactive |
power-pptx keeps the upstream object model and adds slide management — remove, move, reorder, duplicate — plus set_transition for slide transitions, a layout linter, automatic repair, and an HTML import path. Its render_thumbnails renders slides, but through an external LibreOffice and Poppler/PDFium chain rather than a built-in engine, which becomes a deployment question rather than a feature checkbox.
One practical trap worth knowing before you experiment: ps-python-pptx exposes the same pptx import name as the upstream package. Installing both in one environment will not give you both; use separate virtual environments when you want to compare them.
Where the APIs Differ
The round-trip table in the second section answers "what survives a save." This table answers a different question: what each library can actively create, read, and modify. Keep the two separate — in our test, python-pptx preserved every object type it has no API for.
Presentation authoring
| Capability | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Text, images, tables, charts, hyperlinks | Native | Native | Native |
| Speaker notes | Native | Native | Native |
| Video insertion | Experimental (add_movie); manual sizing and poster frame |
Native | Native (InsertVideo) |
| New slides | Native | Native | Native |
| Delete / reorder / duplicate slides | No | remove / move / reorder / duplicate |
Native |
| Shape animations | No | No | Native (Timeline) |
| Slide transitions | No | set_transition |
Native (SlideShowTransition) |
| SmartArt creation | No | No | Native (InsertSmartArt) |
| Comments | No | No | Native (AddComment / DeleteComment) |
Document processing
| Capability | python-pptx | power-pptx | Spire.Presentation |
|---|---|---|---|
| Open and edit an existing PPTX | Native | Native | Native |
| PDF / image / SVG / HTML export | No | render_thumbnails (external runtime) |
Native (PDF / image / SVG / HTML) |
| Merge / split presentations | Manual XML and relationship copying | duplicate helpers; merging still manual |
Native |
| Encryption / password protection | No | No | Native (Encrypt / Protect) |
| Digital signatures | No | No | Read / verify / remove; creation not found in our inspection |
Two rows need honest framing. Watermarking does not appear in the matrix because none of the three ships a dedicated watermark API — PowerPoint itself has no built-in watermark feature, and the working approach (placing a shape, then filling it with text or an image) is available in all three libraries. Digital signatures appear only as read/verify/remove because that is what we could confirm; we are not claiming the ability to create them.
Notice how the tables read against each other. The capabilities where python-pptx and power-pptx show "No" are precisely the object types that survived our round-trip test intact. What is missing is not safety — it is the handle to do the work.
The Cost of Filling Those Gaps
Byte-level preservation does not make a library more capable, and an absent API does not make it destructive. Whether the gap matters depends entirely on what your pipeline is asked to do.
If your presentations are built from fixed templates and Python only swaps titles, numbers, and images — with the animated, final file handed back to PowerPoint for delivery — python-pptx already fits, and its "missing" APIs never come up. Preserved-but-untouched is exactly the behavior you want.
The gap becomes real cost when the requirement is to generate or transform the features themselves: authoring animations for generated slides, batch-reordering decks, building SmartArt programmatically, appending review comments from an approval system, exporting finished decks to PDF or images without a desktop Office, or protecting output files. Now every "No" in the matrix converts into one of these workarounds:
| Approach | Extra dependency | Ongoing maintenance |
|---|---|---|
| Raw XML patching on the package | lxml, OOXML spec knowledge | Every PowerPoint format revision can break hand-written timing or SmartArt XML |
| LibreOffice headless for rendering | LibreOffice plus Poppler or PDFium | Version drift, profile isolation, rendering differences from PowerPoint |
| Office COM automation | A licensed desktop Office install | Windows-only, single-instance throughput, COM failures under load |
| A separate tool per conversion or protection step | One more dependency each | Glue code, exception surfaces, file handoffs |
Each of these is a legitimate engineering choice, and teams run them in production every day. The accounting question is whether you want to own that stack — the XML patches, the LibreOffice container, the COM session pool — as part of your product, or as infrastructure around it. A useful mental model: the open-source libraries shift the complexity into your integration code, while a commercial library shifts it into a dependency you license.
Working With a More Complete Presentation API
This is the point where the requirements — not the marketing — bring a commercial library into the picture. Spire.Presentation for Python, E-iceblue's own commercial library, exposes the object types the open-source packages carry but do not model: animation timelines, transitions, SmartArt, comments, encryption, and rendering exports.
The difference shows up in what a pipeline stops needing. A workflow that used to require "python-pptx to edit, LibreOffice to render, a COM script to add animations" can collapse into a single object model:
from spire.presentation import (
Presentation, FileFormat, AnimationEffectType, TransitionType,
)
from spire.presentation.common import PointF, DateTime
pres = Presentation()
pres.LoadFromFile("input.pptx")
# Move the slide at index 1 to index 3. The signature is Move(newIndex, oldIndex).
pres.Slides.Move(3, 1)
first = pres.Slides[0]
first.Timeline.MainSequence.AddEffect(first.Shapes[0], AnimationEffectType.Fade) # demo: choose your target shape
first.SlideShowTransition.Type = TransitionType.Fade
author = pres.CommentAuthors.AddAuthor("Reviewer", "RV")
first.AddComment(
author,
"Check the Q3 figures.",
PointF(100.0, 100.0), # PointF takes floats, not ints
DateTime.Parse("2026-11-23 10:00:00"), # DateTime has no Now(); parse a string
)
pres.SaveToFile("output.pdf", FileFormat.PDF)
pres.Encrypt("demo-password")
pres.SaveToFile("output.pptx", FileFormat.Pptx2013)
pres.Dispose()
In our run, PowerPoint reopened the edited file as 12 slides with three animation sequences, two comments, and two transitioned slides — exactly one of each added to the original file. The new comment's text and author were readable on reopen, and the Fade transition was attached to the first slide.
The PDF and the encrypted PPTX are separate outputs: the PDF is exported before encryption, while the password applies only to the PPTX that is saved afterwards.
The same API family covers the adjacent operations: merging multiple presentations into one deck, converting PowerPoint to PDF in the same process that edits the file, and protecting the result with a password. The objects our matrix flagged — animations, SmartArt diagrams, and comments — are handled by the same object model.
This is not "open source fails." The evidence shows the opposite: the open-source path handles a real and common class of work well. The commercial library earns its place when the task list itself widens, and the alternative is maintaining several integration layers around a library that was never designed for them.
Deployment and Licensing Considerations
python-pptx, power-pptx, and ps-python-pptx are all MIT-licensed. Deployment is a pip install; core PPTX editing does not require Microsoft Office or an external rendering process. The hidden cost sits elsewhere — in the workaround layers you build around the library when a requirement exceeds its API, as described in the previous section.
Spire.Presentation is commercial software: business use falls under its commercial license terms. Evaluation builds add a watermark and may limit output, so the measurements above exclude the watermark; use the free edition or apply for a temporary license for a clean test. Commercial terms and deployment options are on the licensing page. Its runtime also brings deployment considerations: verify the supported platforms for your target environment (Linux servers, containers, Windows) against the product's current requirements.
Choosing an Approach for Your Project
Rather than a persona list, a decision path — each branch follows directly from the evidence above:
- You generate or modify standard slide content — text, images, tables, charts, notes, hyperlinks, video — inside templates that already carry your animations and SmartArt. python-pptx is sufficient. Its round-trip preservation is verified, its dependencies are minimal, and the missing APIs never block this work. If you later need to delete, reorder, or duplicate slides, or set transitions, evaluate power-pptx against the same tests.
- Your slides must be created, not just filled. Animations, SmartArt, and comments are outputs of your pipeline, not artifacts of a template. Evaluate a library with those APIs, or budget for the XML patching that replaces them.
- The pipeline ends in another format or a locked file. PDF, images, or password-protected output without a desktop Office installation. Evaluate a library with native conversion and protection, or plan the LibreOffice and encryption tooling explicitly.
Whatever you choose, run the same test against your own decks: open, save, count objects, diff renders. It answers more than any feature table can. The Spire.Presentation product page and its download package are reasonable starting points if you want to add Spire as another candidate; if your work stays inside python-pptx's object model, the test will tell you that too.
See Also
Python-Excel-Automatisierung, die über einfache Bearbeitung hinausgeht

Jeden Monat dieselbe Excel-Arbeit: die regionalen Verkaufsdateien herunterladen, sie in eine Hauptarbeitsmappe einfügen, die Summen aktualisieren, alles markieren, was falsch aussieht, das PDF per E-Mail versenden und die Kopien des Vormonats archivieren. Nichts davon ist schwierig, und genau das ist das Problem – die Arbeit ist repetitiv, bei manueller Ausführung fehleranfällig und wächst still mit der Anzahl der Dateien. Die Python-Excel-Automatisierung ersetzt diese wiederkehrenden manuellen Schritte durch Skripte, die Arbeitsmappen nach einem Zeitplan lesen, aktualisieren, zusammenführen, prüfen und ausliefern.
Diese Anleitung zeigt jede dieser Aufgaben, umgesetzt mit Spire.XLS for Python 16.8.2 (dem eigenständigen Python-Paket auf PyPI), von einer Zellbearbeitung in fünf Zeilen bis zu einer geplanten Pipeline, die Formeln neu berechnet und PDFs ausliefert. Jeder Ausschnitt unten wurde vor der Veröffentlichung ausgeführt und seine Ausgabedateien geöffnet und überprüft. Nebenbei wird auch erwähnt, wo die anderen gängigen Bibliotheken passen, sodass Sie die Kompromisse sehen und nicht nur eine Produktbroschüre.
Auswahl einer Python-Bibliothek für die Excel-Automatisierung
Python-Excel-Automatisierung eignet sich, wenn eine Aufgabe nach einem Zeitplan wiederholt wird, festen Regeln folgt und Dateien statt Urteilsvermögen betrifft: monatliche Berichtszusammenstellung, wöchentliche Datenprüfungen, Aktualisieren von Zahlen in einer Vorlage, Konvertieren von Arbeitsmappen für nachgelagerte Systeme. Wenn eine Aufgabe jedes Mal ihre Form ändert oder mittendrin eine menschliche Entscheidung erfordert, kostet die Skripterstellung mehr, als sie einspart. Ein Hinweis zur Abgrenzung: Diese Anleitung behandelt die Verarbeitung von Excel-Dateien. Die Automatisierung der Erstellung von Excel-zu-PowerPoint- oder Excel-zu-Word-Dokumenten ist ein verwandtes, aber separates Thema.
Die Wahl der Bibliothek hängt von der Aufgabe ab. Die folgende Tabelle fasst die fünf Bibliotheken zusammen, auf die Sie am wahrscheinlichsten stoßen; jede hat eine Zeile, weil jede eine Spezialität hat.
| Bibliothek | Am besten geeignet für | Wichtige Überlegung |
|---|---|---|
| pandas | Tabellarische Datenanalyse und -transformation | Bewahrt nicht das vollständige Arbeitsmappen-Objektmodell |
| openpyxl | Bearbeiten vorhandener XLSX/XLSM-Arbeitsmappen und Formatierung auf Zellenebene | Keine Formelberechnungs-Engine; eingeschränkte Objektunterstützung (einige Formen gehen beim erneuten Speichern verloren) |
| XlsxWriter | Erstellen neuer XLSX-Berichte mit Formatierung und Diagrammen | Kann vorhandene Arbeitsmappen nicht lesen oder ändern |
| xlwings | Automatisieren einer laufenden Excel-Anwendung und Integrieren von Python in Excel | Die Classic-Edition erfordert Excel auf dem Desktop (der PRO File Reader kann unter Linux ohne Excel ausgeführt werden) |
| Spire.XLS | Formübergreifende Arbeitsmappenverarbeitung, Formelberechnung und Dokumentkonvertierung über eine einheitliche API | Kommerzielle Lizenzierung; Support- und Bereitstellungsbedingungen variieren je nach Plan |
pandas ist kaum zu schlagen für Analysen, die bereits in eine Tabelle passen, openpyxl für Bearbeitungen auf Zellenebene, XlsxWriter zum Schreiben neuer Arbeitsmappen, xlwings zum Steuern von Excel selbst. Jede Bibliothek konzentriert sich auf einen anderen Teil des Workflows, und ihre Kombination bedeutet zusätzliche Abhängigkeiten und Integrationsarbeit zwischen unterschiedlichen Objektmodellen. Spire.XLS bietet eine einzige API für Lesen, Bearbeiten, Berechnen, Konvertieren und Schützen über die unterstützten Formate hinweg – die folgenden Beispiele bleiben alle in einer API.
Wenn Sie die Bibliotheken eingehender vergleichen möchten, statt Implementierungscode zu suchen, lesen Sie unseren Vergleich unter beste Excel-Bibliothek für Python.

Arbeitsmappen mit Python lesen und aktualisieren
Die häufigste Automatisierungsaufgabe ist zugleich die einfachste: eine Arbeitsmappe laden, einige Zellen ändern, speichern. Installieren Sie zuerst das Paket mit pip install Spire.XLS, dann passt die gesamte Aufgabe in wenige Zeilen:
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("sales.xlsx") # load the template
ws = wb.Worksheets[0]
ws.Range["B2"].NumberValue = 150 # update an existing cell
ws.Range["A6"].Text = "Widget E" # append a new row
ws.Range["B6"].NumberValue = 45
ws.Range["C6"].NumberValue = 11.75
ws.Range["D6"].Formula = "=B6*C6" # formulas can be written
ws.Range["D6"].NumberFormat = "#,##0.00"
wb.SaveToFile("sales_updated.xlsx", FileFormat.Version2016)
wb.Dispose() # release the workbook
Einige Lesekonventionen sollten Sie kennen, bevor Sie darauf aufbauen. In der API von Spire.XLS gibt Range[addr].NumberValue den numerischen Wert einer Zelle und NaN zurück, wenn die Zelle Text oder nichts enthält; Range[addr].Text gibt die angezeigte Zeichenfolge zurück; und bei Formelzellen gibt Range[addr].Formula die Formelzeichenfolge zurück, während FormulaNumberValue das berechnete Ergebnis zurückgibt. Das Schreiben einer Formel über .Formula speichert die Formel selbst – um ihr berechnetes Ergebnis in der Datei zu persistieren, siehe den Abschnitt zur Neuberechnung weiter unten in dieser Anleitung.
In unserem Test dieses Ausschnitts blieben der aktualisierte Wert, die angehängte Zeile, ihr Zahlenformat und die vorhandene Kopfzeilenformatierung nach dem Speichern erhalten, und die Formel wurde genau wie geschrieben beibehalten. Beim erneuten Öffnen der gespeicherten Datei mit Spire.XLS und Aufruf von CalculateAllValue() wurde für die angehängte Zelle =B6*C6 528.75 zurückgegeben, und ein unabhängiges Lesen über openpyxl bestätigte dieselben Werte in der gespeicherten Datei.

Excel-Berichte automatisieren und Stapelverarbeitung
Regionale Arbeitsmappen in einem Hauptbericht zusammenführen
Das Zusammenführen der regionalen Dateien in einer Hauptarbeitsmappe ist der Punkt, an dem sich Automatisierung zu bezahlen beginnt. Mit Spire.XLS wird jede Quelldatei nacheinander geladen, ihre Zeilen werden über den zugewiesenen Bereich gelesen, und die Daten landen in einer neuen Arbeitsmappe mit einer Quellspalte, sodass jede Zeile nachvollziehbar bleibt:
import glob, os
from spire.xls import Workbook, FileFormat
master = Workbook()
ms = master.Worksheets[0]
ms.Range["A1"].Text = "Month"
ms.Range["B1"].Text = "Store"
ms.Range["C1"].Text = "Revenue"
ms.Range["D1"].Text = "Source File"
out_row = 2
for path in glob.glob("region_*.xlsx"):
wb = Workbook()
wb.LoadFromFile(path)
ws = wb.Worksheets[0]
for r in range(2, ws.AllocatedRange.RowCount + 1): # skip each file's header
for c in range(1, 4):
src = ws.Range[r, c]
nv = src.NumberValue
if not (isinstance(nv, float) and nv != nv): # NaN means "not a number"
ms.Range[out_row, c].NumberValue = nv
else:
ms.Range[out_row, c].Text = src.Value
ms.Range[out_row, 4].Text = os.path.basename(path)
out_row += 1
wb.Dispose()
master.SaveToFile("master_report.xlsx", FileFormat.Version2016)
master.Dispose()
Im Test mit drei Eingabedateien enthielt die zusammengeführte Ausgabe genau die Summe der Eingabezeilen – insgesamt neun –, die Umsatzspalte enthielt echte Zahlen (sie summierten sich auf 94.298,00 und stimmten auf den Cent mit den Eingaben überein), die Quellspalte ergab genau die drei Dateinamen, und keine Kopfzeile gelangte in die Daten. Das Ergebnis war auch mit openpyxl erneut lesbar, sodass es direkt den nächsten Schritt einer Pipeline speisen kann. Eine Grenze ist zu beachten: Diese Schleife kopiert Zellwerte, nicht die Quellformatierung. Wenn Ihre Quellspalten echte Excel-Datumsangaben, Prozentsätze oder Währungsbeträge enthalten, wenden Sie die passenden Zahlenformate auf die Zielspalten an – in unseren Testdateien ist die Spalte Month Text, daher ist die Kopie exakt.

Formatierte Berichte pro Kunde generieren
Das Zusammenführen liefert einen Datensatz; die Berichtserzeugung macht daraus Lieferobjekte. Eine Haupttabelle zu lesen und pro Kunde eine formatierte Rechnungsarbeitsmappe zu erzeugen ist eine Schleife: die Zeilen gruppieren und dann jede Rechnung mit einem zusammengeführten Titel, einer formatierten Kopfzeile, zahlenformatierten Beträgen und einer Summe per SUM-Formel erstellen:
from spire.xls import Workbook, FileFormat, Color
wb = Workbook()
wb.LoadFromFile("invoice_master.xlsx")
ws = wb.Worksheets[0]
clients = {}
for r in range(2, ws.AllocatedRange.RowCount + 1):
client = ws.Range[r, 1].Value
clients.setdefault(client, []).append(
(ws.Range[r, 2].Value, ws.Range[r, 3].NumberValue))
for client, items in clients.items():
inv = Workbook()
sheet = inv.Worksheets[0]
sheet.Range["A1"].Text = f"Invoice - {client}"
sheet.Range["A1"].Style.Font.IsBold = True
sheet.Range["A1"].Style.Font.Size = 13
sheet.Range["A1:B1"].Merge()
sheet.Range["A3"].Text = "Service"
sheet.Range["B3"].Text = "Amount"
header = sheet.Range["A3:B3"]
header.Style.Color = Color.FromArgb(255, 68, 114, 196)
header.Style.Font.Color = Color.FromArgb(255, 255, 255, 255)
header.Style.Font.IsBold = True
row = 4
for service, amount in items:
sheet.Range[row, 1].Text = service
sheet.Range[row, 2].NumberValue = amount
sheet.Range[row, 2].NumberFormat = "#,##0.00"
row += 1
sheet.Range[row, 1].Text = "Total"
sheet.Range[row, 1].Style.Font.IsBold = True
sheet.Range[row, 2].Formula = f"=SUM(B4:B{row - 1})"
sheet.Range[row, 2].NumberFormat = "#,##0.00"
sheet.SetColumnWidth(1, 22)
sheet.SetColumnWidth(2, 14)
inv.SaveToFile(f"{client.replace(' ', '_').lower()}_invoice.xlsx",
FileFormat.Version2016)
inv.Dispose()
In unserem Test erzeugten drei Kunden drei Arbeitsmappen, der zusammengeführte Titel und die formatierte Kopfzeile wurden übernommen, und die Formel =SUM überstand das Speichern. Ein praktischer Hinweis: Der Dateiname stammt direkt vom Kundennamen – wenn echte Namen Zeichen wie / oder : enthalten können, bereinigen Sie sie, bevor Sie den Dateinamen erstellen. Nach CalculateAllValue() betrug die Summe der Acme-Rechnung 8.680,50 – genau passend zu den drei Positionen –, und die Formelzeichenfolge war weiterhin in der Zelle, sodass Excel sie beim Öffnen weiterhin neu berechnet. Bei komplexen Vorlagen mit Diagrammen oder Pivot-Tabellen wird der Roundtrip zur Belastungsprobe für die Objekterhaltung; das wird im erweiterten Abschnitt weiter unten behandelt.
Excel-Daten validieren und Ausnahmen hervorheben
Automatisierung bedeutet nicht nur, Dateien zu erzeugen; sie bedeutet auch, sie zu prüfen. Ein nützliches Muster ist ein Scan-Schritt, der eine Arbeitsmappe durchläuft, Ihre Datenqualitätsregeln anwendet und die Zeilen markiert, die sie verletzen, sodass eine Person markierte Zeilen prüft, anstatt alles erneut zu lesen. Dies ist Datenprüfung mit sichtbaren Markierungen – sie ersetzt nicht die Datenüberprüfungsfunktion von Excel, die steuert, was ein Benutzer in eine Zelle eingeben kann. Mit Spire.XLS liest der Scan Zellen über NumberValue, das für Text- und leere Zellen NaN zurückgibt – deshalb meldet die erste Regel unten missing_or_non_numeric, statt zu behaupten, die beiden Fälle unterscheiden zu können – und markiert Fehler über Zellstile:
import math
from spire.xls import Workbook, FileFormat, Color
LIGHT_RED = Color.FromArgb(255, 254, 226, 226)
NOTE_RED = Color.FromArgb(255, 185, 28, 28)
wb = Workbook()
wb.LoadFromFile("payroll.xlsx")
ws = wb.Worksheets[0]
for row in range(2, ws.AllocatedRange.RowCount + 1):
salary = ws.Range[row, 2].NumberValue
bonus = ws.Range[row, 3].NumberValue
reasons = []
if math.isnan(salary) or math.isnan(bonus):
reasons.append("missing_or_non_numeric")
if not math.isnan(salary) and salary > 100000:
reasons.append("outlier")
if not math.isnan(bonus) and bonus < 0:
reasons.append("invalid")
if reasons:
ws.Range[row, 1, row, 3].Style.Color = LIGHT_RED
ws.Range[row, 4].Text = "; ".join(reasons)
ws.Range[row, 4].Style.Font.Color = NOTE_RED
wb.SaveToFile("qa_flagged.xlsx", FileFormat.Version2016)
wb.Dispose()
In unseren Testdaten markierte dies korrekt die vier Problemzeilen – zwei mit fehlenden oder nicht numerischen Werten, einen Gehaltsausreißer über dem Schwellenwert, einen negativen Bonus –, ließ die sauberen Zeilen unberührt und schrieb einen Grund pro Zeile in Spalte D, den wir sowohl durch erneutes Öffnen der Datei als auch im zugrunde liegenden XML überprüften. Das erneute Ausführen des Scans auf der unveränderten Testarbeitsmappe ergab dieselben vier markierten Zeilen. Die Regeln hier sind bewusst einfach: Bei echten Gehaltsdaten sind die Schwellenwerte und der Regelsatz der interessante Teil, und sie liegen in Ihrem Code, wo sie versioniert und überprüft werden können.

Dieses Muster lässt sich gut mit den vorherigen Abschnitten kombinieren: die regionalen Dateien zusammenführen, die kombinierten Daten scannen und die Arbeitsmappe je nach Ergebnis des Scans zur Prüfung oder Auslieferung weiterleiten.
Python-Excel-Automatisierung planen
Ein Skript, das von Hand ausgeführt werden muss, ist nur eine halbe Automatisierung. Die andere Hälfte besteht darin, es dann laufen zu lassen, wenn es laufen soll. Da die obigen Schritte reines Python sind, lässt sich der fertige Workflow – laden, zusammenführen, scannen, erzeugen, ausliefern – in eine Funktion packen, die ein Betriebssystem-Scheduler selbstständig ausführen kann:
| Methode | Wie sie ausgeführt wird | Am besten geeignet für |
|---|---|---|
| Windows-Aufgabenplanung | Das Betriebssystem startet das Python-Skript | Wiederkehrende Berichte unter Windows |
| cron | Das Betriebssystem startet das Skript unter Linux/macOS | Serverseitige geplante Jobs |
Beide starten Ihr Skript, lassen es seine Arbeit erledigen und beenden sich – kein lang laufender Prozess, um den Sie sich kümmern müssen. Ihr Verhalten bei verpassten Läufen unterscheidet sich jedoch: Die Windows-Aufgabenplanung kann so konfiguriert werden, dass eine Aufgabe so bald wie möglich ausgeführt wird, nachdem ihr geplanter Start verpasst wurde, während standardmäßige cron-Jobs im Allgemeinen keine verpassten Ausführungen nachholen, wenn das System offline war. Ein Bereitstellungshinweis, der später Verwirrung erspart: Spire.XLS verarbeitet Arbeitsmappendateien direkt und benötigt kein installiertes Excel auf dem Desktop, sodass die obigen Skripte auf einem Linux-Server oder in einem Container laufen – und damit den älteren Ansatz ersetzen, Desktop-Office über COM-Automatisierung zu skripten. Kein Excel zu benötigen ist jedoch nicht dasselbe wie das Reproduzieren des gesamten Excel-Verhaltens; der nächste Abschnitt behandelt die Teile, die wirklich schwer zu reproduzieren sind.
Erweiterte Aufgaben der Excel-Automatisierung behandeln
Für viele Pipelines sind die obigen Abschnitte die fertige Antwort. Manche Workflows fügen weiter Anforderungen hinzu – mehr Eingabeformate, Formeln, die neu berechnet werden müssen, PDF-Auslieferung, geschützte Archive. Dieser Abschnitt behandelt diese Punkte mit Code, der gegen Spire.XLS for Python 16.8.2 getestet wurde (das eigenständige Python-Paket auf PyPI). Es ist ein Implementierungsweg für die schwierigeren Anforderungen, nicht die Standardantwort auf jede Aufgabe auf dieser Seite.
Mit mehreren Dateiformaten arbeiten
Es ist üblich, dass ein vorgelagertes System .xls, .xlsb oder .ods exportiert, während Ihre Pipeline .xlsx erwartet. Jedes Format bedeutet normalerweise ein anderes Python-Paket und eine andere Engine. Spire.XLS verarbeitet sie über dieselbe Arbeitsmappen-API – und in unseren Tests mit 16.8.2 lud und speicherte dasselbe Arbeitsmappenobjekt .xls, .ods, .xlsx und .xlsb (FileFormat.Xlsb2007 / Xlsb2010) und führte .xls, .ods und .xlsb mit intakten Werten wieder in ihre eigenen Formate zurück. Die von uns geschriebenen .xlsb-Dateien ließen sich auch in Excel ohne Probleme erneut öffnen, obwohl der Open-Source-Parser pyxlsb sie nicht lesen konnte – es lohnt sich, dies gegen Ihre eigenen nachgelagerten Reader zu prüfen, bevor Sie sich festlegen.
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("legacy_input.xls") # also reads .xlsb and .ods
wb.SaveToFile("converted.xlsx", FileFormat.Version2016)
wb.Dispose()
Eine Unterscheidung, die man im Auge behalten sollte: „Im Originalformat bearbeiten und speichern“ und „für die Auslieferung konvertieren“ sind unterschiedliche Ziele. Ersteres behält eine Arbeitsdatei an Ort und Stelle; Letzteres versorgt einen nachgelagerten Konsumenten. Beide kommen im End-to-End-Beispiel unten vor.
Formeln neu berechnen
Bibliotheken, die Formeln schreiben, schreiben nicht unbedingt Ergebnisse. openpyxl zum Beispiel behält eine Formelzeichenfolge bei, speichert aber keinen berechneten Wert, sodass ein nachgelagerter Reader, der nicht berechnet, nichts sieht – ein echtes Problem, wenn eine geplante Pipeline Dateien an Systeme ausliefert, die die Datei unverändert lesen.
Eine Berechnungs-Engine schließt diese Lücke:
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("model.xlsx") # formulas written by another tool, no cached values
wb.CalculateAllValue() # compute every formula
wb.SaveToFile("model_calculated.xlsx", FileFormat.Version2016)
wb.Dispose()
Wir haben beide Seiten davon überprüft. Beim Laden berechnet Spire.XLS standardmäßig bereits im Speicher (RecalculateOnOpen ist aktiviert), sodass FormulaNumberValue sofort berechnete Zahlen liest – aber das Persistieren der Ergebnisse in die Datei erfordert den expliziten Aufruf CalculateAllValue() vor dem Speichern. Mit dem Aufruf enthielt die gespeicherte Datei die berechneten Werte, was unser openpyxl-Reader mit data_only=True bestätigte; ohne ihn lasen dieselben Zellen None. Nach diesem Speichern kann jede Bibliothek die Ergebnisse lesen. Eine Grenze, die es wert ist, genannt zu werden: Die Berechnung deckt die Funktionen und Abhängigkeiten ab, die die Engine unterstützt – Arbeitsmappen, die auf externe Links, Add-In-Funktionen oder Funktionen außerhalb des unterstützten Satzes angewiesen sind, sollten gegen Ihre eigenen Dateien getestet werden, bevor Sie sich auf die berechnete Ausgabe verlassen.

Excel-Berichte nach PDF exportieren
Geplante Berichte enden üblicherweise als PDF für Personen, die die Arbeitsmappe nie öffnen. Eine Tabellenkalkulation originalgetreu wiederzugeben – Spaltenbreiten, Schriftarten, Diagramme – ist genau der Teil, den generische Konvertierungswerkzeuge falsch machen. Mit Spire.XLS rendert das Arbeitsblatt sich selbst, nachdem zuerst die Seiteneinrichtung festgelegt wurde:
from spire.xls import Workbook, PageOrientationType
wb = Workbook()
wb.LoadFromFile("model_calculated.xlsx")
sheet = wb.Worksheets[0]
sheet.PageSetup.Orientation = PageOrientationType.Portrait
sheet.PageSetup.FitToPagesWide = 1
sheet.PageSetup.FitToPagesTall = 1
sheet.SaveToPdf("report.pdf") # worksheet-level export
wb.Dispose()
Die Einstellungen FitToPagesWide und FitToPagesTall skalieren das Arbeitsblatt so, dass es in eine Seite Breite und eine Seite Höhe passt, wodurch verhindert wird, dass Spalten über Seiten hinweg aufgeteilt werden – bei sehr breiten Blättern kann der verkleinerte Text jedoch zu klein werden, um bequem lesbar zu sein. Das SaveToPdf auf Arbeitsblattebene liefert genau das gewählte Blatt statt aller Arbeitsblätter in der Arbeitsmappe. In unserem Test ergab das exportierte PDF eine einzelne Seite mit dem Titel, der vollständigen Tabelle einschließlich der neu berechneten Summen und dem gerenderten Diagramm. Einzelheiten zum Layout finden Sie unter Excel in Python nach PDF konvertieren.

Mit Diagrammen und Pivot-Tabellen arbeiten
Berichtsarbeitsmappen enthalten normalerweise Objekte, nicht nur Zellen. In unserer Testarbeitsmappe blieben bei einem Roundtrip durch Spire.XLS 16.8.2 die Diagrammteile auf XML-Ebene intakt, und das Diagramm wurde vollständig gerendert, als die Datei in Excel erneut geöffnet wurde. Wir geben das als Ergebnis für unsere Testdateien an, nicht als Garantie für jedes DrawingML-Objekt – komplexe Formen sollten gegen Ihre eigenen Dateien überprüft werden, derselbe Rat gilt für jede Bibliothek. Die Arbeitsmappen-API von Spire.XLS deckt auch Pivot-Tabellen und Pivot-Diagramme ab – Erstellung, Aktualisierung und Feldoperationen; zur Pivot-Tabellen-Seite siehe Pivot-Tabellen in Excel erstellen oder bedienen. Unsere Testdatei enthielt keine Pivot-Tabelle, daher sollten Sie Ihre eigenen Arbeitsmappen durch den Roundtrip laufen lassen, bevor Sie sich festlegen.
Excel-Arbeitsmappen schützen
Archivierte oder per E-Mail versendete Berichte benötigen oft ein Öffnungskennwort. Ein Aufruf legt es fest:
wb.Protect("Report2026")
wb.SaveToFile("protected_report.xlsx", FileFormat.Version2016)
wb.Dispose()
In unserem Test ließ sich die Datei ohne das Kennwort nicht öffnen – auch nicht in openpyxl, das bei dem verschlüsselten Container einen Fehler auslöste. Das erneute Lesen über dieselbe Bibliothek erfordert die Eigenschaft OpenPassword. Wenn eine Pipeline also geschützte Dateien schützt und später liest, muss die Leseseite der Toolchain dies unterstützen.
Auswahl einer Bibliothek für die produktive Excel-Automatisierung
Über die API-Abdeckung hinaus benötigt eine Produktionsabhängigkeit auch einen Wartungsplan. Spire.XLS for Python veröffentlicht weiterhin Releases – 16.8.2 (August 2026, die in dieser Anleitung getestete Version) fügte beispielsweise Unterstützung für die TEXTSPLIT-Formel hinzu. Die Lizenzierung ist unbefristet: Die Lizenz deckt die fortgesetzte Nutzung zu ihren Bedingungen ab, während der Zugriff auf neuere Releases der Update-Berechtigung folgt – ein Jahr Produktupdates und Hotfixes ist in den Lizenzplänen enthalten, und kommerzieller Support bietet Ihnen einen definierten Herstellerkanal für Format-, Berechnungs- oder Konvertierungsprobleme statt eines Community-Trackers. Antwortzeitziele, Supportkanäle und Extras je nach Plan variieren nach Stufe – siehe die Seite Lizenzpläne für Spire.XLS for Python oder den Vergleich beste Excel-Bibliothek für Python, um zu sehen, wie Entwickleranzahl und Bereitstellungsumfang die Wahl beeinflussen.
Ein End-to-End-Beispiel
Die obigen Bausteine kombinieren sich zu einem Konvertierungs- und Auslieferungs-Workflow: eine alte .xlsb-Eingabe lesen, einen Wert aktualisieren, neu berechnen und sowohl ein PDF als auch eine passwortgeschützte .xlsx ausliefern:
from spire.xls import Workbook, FileFormat, PageOrientationType
wb = Workbook()
wb.LoadFromFile("monthly_input.xlsb") # read the binary format
sheet = wb.Worksheets[0]
sheet.Range["B2"].NumberValue = 125000 # update an input cell
wb.CalculateAllValue() # persist computed results
sheet.PageSetup.Orientation = PageOrientationType.Portrait
sheet.PageSetup.FitToPagesWide = 1
sheet.PageSetup.FitToPagesTall = 1
sheet.SaveToPdf("monthly_report.pdf") # deliverable 1: PDF
wb.Protect("Report2026") # deliverable 2: protected xlsx
wb.SaveToFile("monthly_report.xlsx", FileFormat.Version2016)
wb.Dispose() # release the workbook

Jeder Schritt wurde in unserer Testumgebung mit Spire.XLS for Python 16.8.2 und Python 3.13 verifiziert. Wenn dieser Workflow Ihren Anforderungen entspricht, erkunden Sie Spire.XLS for Python. Die kostenlose Edition reicht für eine grundlegende Evaluierung; für kommerzielle Projekte fordern Sie eine einmonatige temporäre Lizenz an und testen Sie die vollständige API gegen Ihre eigenen Arbeitsmappen, bevor Sie eine Produktionslizenz wählen (prüfen Sie die offizielle Seite auf aktuelle Bedingungen).
Häufig gestellte Fragen
Kann Python Excel automatisieren, ohne dass Excel installiert ist?
Ja, für die Dateiverarbeitung – Spire.XLS liest und schreibt Arbeitsmappendateien direkt, und keines der Beispiele hier benötigte Excel auf dem Desktop. Die Ausnahme ist xlwings Classic, das die laufende Excel-Anwendung steuert. „Kein Excel erforderlich“ bezieht sich auf das Ausführen des Codes, nicht auf das Reproduzieren jedes Excel-Verhaltens.
Welche Python-Bibliothek ist am besten für die Excel-Automatisierung geeignet?
Das hängt von der Aufgabe ab: pandas für Analysen, openpyxl für Bearbeitungen auf Zellenebene in .xlsx, XlsxWriter für neue formatierte Arbeitsmappen, xlwings zum Steuern von Excel selbst. Für eine einzige API über Lesen, Bearbeiten, Berechnen, Konvertieren und Schützen hinweg sehen Sie unseren Vergleich beste Excel-Bibliothek für Python.
Kann openpyxl Excel-Formeln neu berechnen?
Nein – es behält Formelzeichenfolgen bei, hat aber keine Berechnungs-Engine, und von openpyxl geschriebene Formeln enthalten keine zwischengespeicherten Ergebnisse; data_only=True liest nur in der Datei gespeicherte Caches und liest für diese Zellen daher None. Zum Berechnen und Persistieren von Ergebnissen siehe Formeln in Excel hinzufügen oder lesen.
Wie plane ich ein Python-Excel-Skript?
Verwenden Sie die Windows-Aufgabenplanung oder cron, damit das Betriebssystem das Skript startet – beachten Sie, dass die Aufgabenplanung so eingestellt werden kann, dass verpasste Aufgaben erneut ausgeführt werden, während standardmäßiges cron verpasste Läufe nicht nachholt, wenn der Rechner offline war. Da das Skript Arbeitsmappendateien direkt verarbeitet, ist auf dem ausführenden Rechner kein Excel auf dem Desktop erforderlich.
Wie kann ich Excel mit Python nach PDF konvertieren?
Legen Sie die Seiteneinrichtung fest (Ausrichtung, Anpassen an Seite) und exportieren Sie das Arbeitsblatt direkt mit einer Bibliothek, die PDFs selbst rendert. Der Open-Source-Weg erfordert eine separate Konvertierungsbibliothek, bei der Sie das Layout selbst handhaben. Details unter Excel in Python nach PDF konvertieren.
Fazit
Die Python-Excel-Automatisierung reicht von einer Zellbearbeitung in fünf Zeilen bis zu einer geplanten Pipeline, die Dateien zusammenführt, fehlerhafte Daten markiert, Formeln neu berechnet und PDFs sowie geschützte Arbeitsmappen ausliefert. pandas, openpyxl und ihre Nachbarn bleiben starke Wahlmöglichkeiten für Analysen und Bearbeitungen einzelner Aufgaben. Wenn die Aufgabe zu einem Workflow wird – mehrere Formate hinein, berechnete Ergebnisse hinaus, PDFs und geschützte Archive nach Zeitplan ausgeliefert – ist eine einheitliche Arbeitsmappen-API mit gepflegten Releases und einem Supportkanal das, was sie in der Produktion trägt, und genau das haben die Beispiele für Spire.XLS for Python in dieser Anleitung gezeigt.
Automação do Excel com Python que vai além da edição básica

Todos os meses trazem o mesmo trabalho no Excel: baixar os arquivos regionais de vendas, colá-los em uma pasta de trabalho mestre, atualizar os totais, sinalizar qualquer coisa que pareça errada, enviar o PDF por e-mail e arquivar as cópias do mês anterior. Nada disso é difícil, e esse é exatamente o problema — o trabalho é repetitivo, sujeito a erros quando feito manualmente e cresce silenciosamente à medida que o número de arquivos aumenta. A automação do Excel com Python substitui essas etapas manuais recorrentes por scripts que leem, atualizam, combinam, verificam e entregam pastas de trabalho em uma programação.
Este guia mostra cada uma dessas tarefas implementada com Spire.XLS for Python 16.8.2 (o pacote Python independente no PyPI), desde uma edição de célula em cinco linhas de código até um pipeline agendado que recalcula fórmulas e entrega PDFs. Cada trecho abaixo foi executado, e seus arquivos de saída foram abertos e verificados, antes da publicação. Ao longo do caminho, ele também observa onde as outras bibliotecas comuns se encaixam, para que você veja as compensações em vez de um folheto de produto.
Escolhendo uma biblioteca Python para automação do Excel
A automação do Excel com Python é uma boa opção quando uma tarefa é repetida em uma programação, segue regras fixas e envolve arquivos em vez de julgamento: montagem de relatórios mensais, verificações semanais de dados, atualização de números em um modelo, conversão de pastas de trabalho para sistemas downstream. Se uma tarefa muda de forma toda vez ou precisa de uma decisão humana no meio, criar um script custará mais do que economiza. Uma observação de limite: este guia cobre o processamento de arquivos do Excel. Automatizar a geração de documentos do Excel para PowerPoint ou do Excel para Word é um tópico relacionado, mas separado.
A escolha da biblioteca depende do trabalho. A tabela abaixo resume as cinco bibliotecas que você provavelmente encontrará; cada uma tem uma linha porque cada uma tem uma especialidade.
| Biblioteca | Melhor para | Consideração principal |
|---|---|---|
| pandas | Análise e transformação de dados tabulares | Não preserva o modelo de objeto completo da pasta de trabalho |
| openpyxl | Edição de pastas de trabalho XLSX/XLSM existentes e formatação em nível de célula | Sem mecanismo de cálculo de fórmulas; suporte limitado a objetos (algumas formas são perdidas ao salvar novamente) |
| XlsxWriter | Criação de novos relatórios XLSX com formatação e gráficos | Não consegue ler ou modificar pastas de trabalho existentes |
| xlwings | Automação de um aplicativo Excel em execução e integração do Python com o Excel | A edição Classic exige o Excel para desktop (o PRO File Reader pode ser executado no Linux sem ele) |
| Spire.XLS | Processamento de pastas de trabalho entre formatos, cálculo de fórmulas e conversão de documentos por meio de uma API unificada | Licenciamento comercial; termos de suporte e implantação variam conforme o plano |
pandas é difícil de superar para análises que já se encaixam em uma tabela, openpyxl para edições no nível de célula, XlsxWriter para gravar novas pastas de trabalho, xlwings para controlar o próprio Excel. Cada um se concentra em uma parte diferente do fluxo de trabalho, e combiná-los significa dependências extras e trabalho de integração entre modelos de objetos diferentes. O Spire.XLS oferece uma única API que cobre leitura, edição, cálculo, conversão e proteção nos formatos suportados — os exemplos abaixo mantêm tudo em uma só.
Se você está comparando as bibliotecas em profundidade em vez de procurar código de implementação, consulte nossa comparação em melhor biblioteca Excel para Python.

Leitura e atualização de pastas de trabalho do Excel com Python
A tarefa de automação mais comum também é a mais simples: carregar uma pasta de trabalho, alterar algumas células, salvá-la. Instale o pacote primeiro com pip install Spire.XLS, e todo o trabalho cabe em algumas linhas:
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("sales.xlsx") # load the template
ws = wb.Worksheets[0]
ws.Range["B2"].NumberValue = 150 # update an existing cell
ws.Range["A6"].Text = "Widget E" # append a new row
ws.Range["B6"].NumberValue = 45
ws.Range["C6"].NumberValue = 11.75
ws.Range["D6"].Formula = "=B6*C6" # formulas can be written
ws.Range["D6"].NumberFormat = "#,##0.00"
wb.SaveToFile("sales_updated.xlsx", FileFormat.Version2016)
wb.Dispose() # release the workbook
Algumas convenções de leitura vale a pena conhecer antes de construir sobre isso. Na API do Spire.XLS, Range[addr].NumberValue retorna o valor numérico de uma célula e NaN quando a célula contém texto ou nada; Range[addr].Text retorna a string exibida; e, para células de fórmula, Range[addr].Formula retorna a string da fórmula enquanto FormulaNumberValue retorna o resultado calculado. Gravar uma fórmula por meio de .Formula armazena a própria fórmula — para persistir seu resultado computado no arquivo, consulte a seção de recálculo mais adiante neste guia.
Em nosso teste deste trecho, o valor atualizado, a linha anexada, seu formato numérico e o estilo de cabeçalho existente sobreviveram ao salvamento, e a fórmula foi preservada exatamente como escrita. Reabrir o arquivo salvo com Spire.XLS e chamar CalculateAllValue() retornou 528,75 para a célula anexada =B6*C6, e uma leitura independente via openpyxl confirmou os mesmos valores no arquivo salvo.

Automatizando relatórios do Excel e processamento em lote
Combinando pastas de trabalho regionais em um relatório mestre
Combinar os arquivos regionais em uma pasta de trabalho mestre é onde a automação começa a se pagar. Com o Spire.XLS, cada arquivo de origem é carregado por vez, suas linhas são lidas por meio do intervalo alocado, e os dados chegam a uma nova pasta de trabalho com uma coluna de origem para que cada linha permaneça rastreável:
import glob, os
from spire.xls import Workbook, FileFormat
master = Workbook()
ms = master.Worksheets[0]
ms.Range["A1"].Text = "Month"
ms.Range["B1"].Text = "Store"
ms.Range["C1"].Text = "Revenue"
ms.Range["D1"].Text = "Source File"
out_row = 2
for path in glob.glob("region_*.xlsx"):
wb = Workbook()
wb.LoadFromFile(path)
ws = wb.Worksheets[0]
for r in range(2, ws.AllocatedRange.RowCount + 1): # skip each file's header
for c in range(1, 4):
src = ws.Range[r, c]
nv = src.NumberValue
if not (isinstance(nv, float) and nv != nv): # NaN means "not a number"
ms.Range[out_row, c].NumberValue = nv
else:
ms.Range[out_row, c].Text = src.Value
ms.Range[out_row, 4].Text = os.path.basename(path)
out_row += 1
wb.Dispose()
master.SaveToFile("master_report.xlsx", FileFormat.Version2016)
master.Dispose()
Em nosso teste com três arquivos de entrada, a saída mesclada continha exatamente a soma das linhas de entrada — nove no total —, a coluna de receita continha números reais (somaram 94.298,00, correspondendo às entradas centavo a centavo), a coluna de origem foi resolvida para exatamente os três nomes de arquivo, e nenhuma linha de cabeçalho vazou para os dados. O resultado também pôde ser relido pelo openpyxl, então ele pode alimentar a próxima etapa de um pipeline diretamente. Um limite a observar: este loop copia valores de células, não a formatação de origem. Se suas colunas de origem contiverem datas reais do Excel, percentuais ou valores de moeda, aplique os formatos numéricos correspondentes às colunas de destino — em nossos fixtures, a coluna Month é texto, então a cópia é exata.

Gerando relatórios formatados por cliente
A mesclagem fornece um conjunto de dados; a geração de relatórios o transforma em entregáveis. Ler uma tabela mestre e produzir uma pasta de trabalho de fatura formatada por cliente é um loop: agrupe as linhas e então construa cada fatura com um título mesclado, uma linha de cabeçalho estilizada, valores com formato numérico e um total SUM:
from spire.xls import Workbook, FileFormat, Color
wb = Workbook()
wb.LoadFromFile("invoice_master.xlsx")
ws = wb.Worksheets[0]
clients = {}
for r in range(2, ws.AllocatedRange.RowCount + 1):
client = ws.Range[r, 1].Value
clients.setdefault(client, []).append(
(ws.Range[r, 2].Value, ws.Range[r, 3].NumberValue))
for client, items in clients.items():
inv = Workbook()
sheet = inv.Worksheets[0]
sheet.Range["A1"].Text = f"Invoice - {client}"
sheet.Range["A1"].Style.Font.IsBold = True
sheet.Range["A1"].Style.Font.Size = 13
sheet.Range["A1:B1"].Merge()
sheet.Range["A3"].Text = "Service"
sheet.Range["B3"].Text = "Amount"
header = sheet.Range["A3:B3"]
header.Style.Color = Color.FromArgb(255, 68, 114, 196)
header.Style.Font.Color = Color.FromArgb(255, 255, 255, 255)
header.Style.Font.IsBold = True
row = 4
for service, amount in items:
sheet.Range[row, 1].Text = service
sheet.Range[row, 2].NumberValue = amount
sheet.Range[row, 2].NumberFormat = "#,##0.00"
row += 1
sheet.Range[row, 1].Text = "Total"
sheet.Range[row, 1].Style.Font.IsBold = True
sheet.Range[row, 2].Formula = f"=SUM(B4:B{row - 1})"
sheet.Range[row, 2].NumberFormat = "#,##0.00"
sheet.SetColumnWidth(1, 22)
sheet.SetColumnWidth(2, 14)
inv.SaveToFile(f"{client.replace(' ', '_').lower()}_invoice.xlsx",
FileFormat.Version2016)
inv.Dispose()
Em nosso teste, três clientes produziram três pastas de trabalho, o título mesclado e o cabeçalho estilizado foram mantidos, e a fórmula =SUM sobreviveu ao salvamento. Uma observação prática: o nome do arquivo vem diretamente do nome do cliente — se nomes reais puderem conter caracteres como / ou :, sanitize-os antes de montar o nome do arquivo. Após CalculateAllValue(), o total da fatura da Acme ficou em 8.680,50 — correspondendo exatamente aos três itens de linha — e a string da fórmula ainda estava na célula, então o Excel continua recalculando-a ao abrir. Para modelos complexos com gráficos ou tabelas dinâmicas, a ida e volta é onde a preservação de objetos é testada; isso é abordado na seção avançada abaixo.
Validando dados do Excel e destacando exceções
A automação não se resume a produzir arquivos; ela também serve para verificá-los. Um padrão útil é uma etapa de verificação que percorre uma pasta de trabalho, aplica suas regras de qualidade de dados e marca as linhas que falham, para que uma pessoa revise as linhas sinalizadas em vez de reler tudo. Esta é uma verificação de dados com marcadores visíveis — ela não substitui o recurso Validação de Dados do Excel, que controla o que um usuário pode digitar em uma célula. Com o Spire.XLS, a verificação lê células por meio de NumberValue, que retorna NaN tanto para texto quanto para células vazias — então a primeira regra abaixo relata missing_or_non_numeric em vez de afirmar distinguir os dois casos — e marca falhas por meio de estilos de célula:
import math
from spire.xls import Workbook, FileFormat, Color
LIGHT_RED = Color.FromArgb(255, 254, 226, 226)
NOTE_RED = Color.FromArgb(255, 185, 28, 28)
wb = Workbook()
wb.LoadFromFile("payroll.xlsx")
ws = wb.Worksheets[0]
for row in range(2, ws.AllocatedRange.RowCount + 1):
salary = ws.Range[row, 2].NumberValue
bonus = ws.Range[row, 3].NumberValue
reasons = []
if math.isnan(salary) or math.isnan(bonus):
reasons.append("missing_or_non_numeric")
if not math.isnan(salary) and salary > 100000:
reasons.append("outlier")
if not math.isnan(bonus) and bonus < 0:
reasons.append("invalid")
if reasons:
ws.Range[row, 1, row, 3].Style.Color = LIGHT_RED
ws.Range[row, 4].Text = "; ".join(reasons)
ws.Range[row, 4].Style.Font.Color = NOTE_RED
wb.SaveToFile("qa_flagged.xlsx", FileFormat.Version2016)
wb.Dispose()
Em nossos dados de teste, isso sinalizou corretamente as quatro linhas problemáticas — duas com valores ausentes ou não numéricos, um outlier de salário acima do limite, um bônus negativo — deixou as linhas limpas intactas e gravou um motivo por linha na coluna D, o que verificamos tanto reabrindo o arquivo quanto no XML subjacente. Reexecutar a verificação na pasta de trabalho de teste inalterada produziu as mesmas quatro linhas sinalizadas. As regras aqui são deliberadamente simples: para dados reais de folha de pagamento, os limites e o conjunto de regras são a parte interessante, e eles ficam no seu código, onde podem ser versionados e revisados.

Esse padrão se compõe bem com as seções anteriores: combine os arquivos regionais, verifique os dados combinados e encaminhe a pasta de trabalho para revisão ou entrega, dependendo do que a verificação encontrar.
Agendando a automação do Excel com Python
Um script que precisa ser executado manualmente é apenas metade de uma automação. A outra metade é fazê-lo rodar quando deveria. Como as etapas acima são Python puro, o fluxo de trabalho finalizado — carregar, combinar, verificar, gerar, entregar — cabe em uma função que um agendador do sistema operacional pode executar sozinho:
| Método | Como é executado | Melhor para |
|---|---|---|
| Windows Task Scheduler | O sistema operacional inicia o script Python | Relatórios recorrentes no Windows |
| cron | O sistema operacional inicia o script no Linux/macOS | Tarefas agendadas no lado do servidor |
Ambos iniciam seu script, deixam-no fazer seu trabalho e encerram — sem processo de longa duração para monitorar. O comportamento em caso de execução perdida, porém, difere: o Windows Task Scheduler pode ser configurado para executar uma tarefa assim que possível após o horário agendado ter sido perdido, enquanto trabalhos cron padrão geralmente não recuperam execuções perdidas enquanto o sistema estava offline. Uma observação de implantação que evita confusão depois: o Spire.XLS processa arquivos de pasta de trabalho diretamente e não precisa do Excel para desktop instalado, então os scripts acima são executados em um servidor Linux ou em um contêiner — substituindo a abordagem mais antiga de criar scripts para o Office desktop via automação COM. Não precisar do Excel, porém, não é o mesmo que reproduzir todo o comportamento do Excel; a próxima seção trata das partes que são genuinamente difíceis de reproduzir.
Lidando com tarefas avançadas de automação do Excel
Para muitos pipelines, as seções acima são a resposta final. Alguns fluxos de trabalho continuam adicionando requisitos — mais formatos de entrada, fórmulas que precisam ser recalculadas, entrega em PDF, arquivos protegidos. Esta seção percorre esses pontos com código testado com Spire.XLS for Python 16.8.2 (o pacote Python independente no PyPI). É um caminho de implementação para os requisitos mais difíceis, não a resposta padrão para todas as tarefas nesta página.
Trabalhando com vários formatos de arquivo
É comum que um sistema upstream exporte .xls, .xlsb ou .ods enquanto seu pipeline espera .xlsx. Cada formato geralmente significa um pacote e um mecanismo Python diferentes. O Spire.XLS lida com eles por meio da mesma API de pasta de trabalho — e, em nossos testes com a versão 16.8.2, o mesmo objeto de pasta de trabalho carregou e salvou .xls, .ods, .xlsx e .xlsb (FileFormat.Xlsb2007 / Xlsb2010), e fez round-trip de .xls, .ods e .xlsb para seus próprios formatos com valores intactos. Os arquivos .xlsb que gravamos também reabriram no Excel sem problemas, embora o parser de código aberto pyxlsb não tenha conseguido lê-los — vale verificar com seus próprios leitores downstream antes de assumir o compromisso.
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("legacy_input.xls") # also reads .xlsb and .ods
wb.SaveToFile("converted.xlsx", FileFormat.Version2016)
wb.Dispose()
Uma distinção que vale manter: "editar e salvar de volta no formato original" e "converter para entrega" são objetivos diferentes. O primeiro mantém um arquivo de trabalho no lugar; o segundo alimenta um consumidor downstream. Ambos aparecem no exemplo de ponta a ponta abaixo.
Recalculando fórmulas
Bibliotecas que gravam fórmulas não necessariamente gravam resultados. O openpyxl, por exemplo, preserva uma string de fórmula, mas não armazena nenhum valor calculado, então um leitor downstream que não calcula não vê nada — um problema real quando um pipeline agendado entrega arquivos a sistemas que leem o arquivo como está.
Um mecanismo de cálculo fecha essa lacuna:
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("model.xlsx") # formulas written by another tool, no cached values
wb.CalculateAllValue() # compute every formula
wb.SaveToFile("model_calculated.xlsx", FileFormat.Version2016)
wb.Dispose()
Verificamos os dois lados disso. Ao carregar, o Spire.XLS já calcula na memória por padrão (RecalculateOnOpen está ativado), então FormulaNumberValue lê números computados imediatamente — mas persistir resultados no arquivo exige a chamada explícita CalculateAllValue() antes de salvar. Com a chamada, o arquivo salvo continha os valores computados, o que nosso leitor openpyxl com data_only=True confirmou; sem ela, as mesmas células liam None. Após esse salvamento, qualquer biblioteca pode ler os resultados. Um limite que vale declarar: o cálculo cobre as funções e dependências suportadas pelo mecanismo — pastas de trabalho que dependem de links externos, funções de suplemento ou funções fora do conjunto suportado devem ser testadas com seus próprios arquivos antes de você depender da saída calculada.

Exportando relatórios do Excel para PDF
Relatórios agendados geralmente terminam como um PDF para pessoas que nunca abrem a pasta de trabalho. Renderizar uma planilha fielmente — larguras de coluna, fontes, gráficos — é exatamente a parte em que ferramentas de conversão genéricas erram. Com o Spire.XLS, a planilha se renderiza sozinha, com a configuração de página definida primeiro:
from spire.xls import Workbook, PageOrientationType
wb = Workbook()
wb.LoadFromFile("model_calculated.xlsx")
sheet = wb.Worksheets[0]
sheet.PageSetup.Orientation = PageOrientationType.Portrait
sheet.PageSetup.FitToPagesWide = 1
sheet.PageSetup.FitToPagesTall = 1
sheet.SaveToPdf("report.pdf") # worksheet-level export
wb.Dispose()
As configurações FitToPagesWide e FitToPagesTall dimensionam a planilha para caber em uma página de largura e uma de altura, o que evita que colunas se dividam entre páginas — em planilhas muito largas, porém, o texto reduzido pode ficar pequeno demais para leitura confortável. O SaveToPdf no nível da planilha entrega exatamente a planilha escolhida, e não todas as planilhas da pasta de trabalho. Em nosso teste, o PDF exportado saiu como uma única página com o título, a tabela completa incluindo os totais recalculados e o gráfico renderizado. Para detalhes de layout, consulte converter Excel para PDF em Python.

Trabalhando com gráficos e tabelas dinâmicas
Pastas de trabalho de relatório geralmente carregam objetos, não apenas células. Em nossa pasta de trabalho de teste, um round-trip pelo Spire.XLS 16.8.2 manteve as partes do gráfico intactas no nível do XML, e o gráfico foi renderizado completamente quando o arquivo foi reaberto no Excel. Declaramos isso como um resultado para nossos fixtures, não como garantia para todo objeto DrawingML — formas complexas devem ser verificadas com seus próprios arquivos, o mesmo conselho que se aplica a qualquer biblioteca. A API de pasta de trabalho do Spire.XLS também cobre tabelas dinâmicas e gráficos dinâmicos — criação, atualização e operações de campo; para o lado das tabelas dinâmicas, consulte criar ou operar tabelas dinâmicas no Excel. Nosso fixture não incluía uma tabela dinâmica, então execute suas próprias pastas de trabalho no round-trip antes de assumir o compromisso.
Protegendo pastas de trabalho do Excel
Relatórios arquivados ou enviados por e-mail frequentemente precisam de uma senha de abertura. Uma chamada a define:
wb.Protect("Report2026")
wb.SaveToFile("protected_report.xlsx", FileFormat.Version2016)
wb.Dispose()
Em nosso teste, o arquivo não abria sem a senha — inclusive no openpyxl, que gerou um erro no contêiner criptografado. Lê-lo de volta pela mesma biblioteca exige a propriedade OpenPassword. Portanto, se um pipeline protege e depois lê arquivos protegidos, o lado leitor da cadeia de ferramentas precisa dar suporte a isso.
Escolhendo uma biblioteca para automação do Excel em produção
Além da cobertura da API, uma dependência de produção também precisa de um plano de manutenção. O Spire.XLS for Python continua lançando versões — a 16.8.2 (agosto de 2026, a versão testada ao longo deste guia) adicionou suporte à fórmula TEXTSPLIT, por exemplo. O licenciamento é perpétuo: a licença cobre o uso continuado sob seus termos, enquanto o acesso a novas versões segue o direito de atualização — um ano de atualizações de produto e hotfixes está incluído nos planos de licença, e o suporte comercial oferece um canal definido com o fornecedor para problemas de formato, cálculo ou conversão, em vez de um rastreador da comunidade. Metas de tempo de resposta, canais de suporte e extras por plano variam conforme o nível — consulte a página planos de licença do Spire.XLS for Python, ou a comparação melhor biblioteca Excel para Python para saber como contagens de desenvolvedores e escopo de implantação se encaixam na escolha.
Um exemplo de ponta a ponta
As peças acima se combinam em um fluxo de trabalho de conversão e entrega: ler uma entrada .xlsb legada, atualizar um número, recalcular e entregar tanto um PDF quanto um .xlsx protegido por senha:
from spire.xls import Workbook, FileFormat, PageOrientationType
wb = Workbook()
wb.LoadFromFile("monthly_input.xlsb") # read the binary format
sheet = wb.Worksheets[0]
sheet.Range["B2"].NumberValue = 125000 # update an input cell
wb.CalculateAllValue() # persist computed results
sheet.PageSetup.Orientation = PageOrientationType.Portrait
sheet.PageSetup.FitToPagesWide = 1
sheet.PageSetup.FitToPagesTall = 1
sheet.SaveToPdf("monthly_report.pdf") # deliverable 1: PDF
wb.Protect("Report2026") # deliverable 2: protected xlsx
wb.SaveToFile("monthly_report.xlsx", FileFormat.Version2016)
wb.Dispose() # release the workbook

Cada etapa foi verificada em nosso ambiente de teste usando Spire.XLS for Python 16.8.2 e Python 3.13. Se este fluxo de trabalho corresponde aos seus requisitos, explore o Spire.XLS for Python. A edição gratuita é suficiente para avaliação básica; para projetos comerciais, solicite uma licença temporária de um mês e teste a API completa com suas próprias pastas de trabalho antes de escolher uma licença de produção (verifique a página oficial para os termos atuais).
Perguntas frequentes
O Python pode automatizar o Excel sem o Excel instalado?
Sim, para processamento de arquivos — o Spire.XLS lê e grava arquivos de pasta de trabalho diretamente, e nenhum dos exemplos aqui precisou do Excel para desktop. A exceção é o xlwings Classic, que controla o aplicativo Excel em execução. "Sem necessidade do Excel" diz respeito à execução do código, não à reprodução de todo o comportamento do Excel.
Qual biblioteca Python é melhor para automação do Excel?
Depende do trabalho: pandas para análise, openpyxl para edições de células em .xlsx, XlsxWriter para novas pastas de trabalho formatadas, xlwings para controlar o próprio Excel. Para uma única API de leitura, edição, cálculo, conversão e proteção, consulte nossa comparação melhor biblioteca Excel para Python.
O openpyxl pode recalcular fórmulas do Excel?
Não — ele preserva strings de fórmula, mas não tem mecanismo de cálculo, e fórmulas gravadas pelo openpyxl não carregam resultados em cache; data_only=True lê apenas caches armazenados no arquivo, então lê None para essas células. Para calcular e persistir resultados, consulte adicionar ou ler fórmulas no Excel.
Como agendo um script Python para Excel?
Use o Windows Task Scheduler ou o cron para permitir que o sistema operacional inicie o script — observe que o Task Scheduler pode ser configurado para reexecutar tarefas perdidas, enquanto o cron padrão não recupera execuções perdidas enquanto a máquina estava offline. Como o script processa arquivos de pasta de trabalho diretamente, não é necessário ter o Excel para desktop na máquina que o executa.
Como posso converter Excel para PDF com Python?
Defina a configuração de página (orientação, ajuste à página) e exporte a planilha diretamente com uma biblioteca que renderiza PDFs por conta própria. A rota de código aberto exige uma biblioteca de conversão separada em que você trata o layout. Detalhes em converter Excel para PDF em Python.
Conclusão
A automação do Excel com Python abrange tudo, desde uma edição de célula em cinco linhas até um pipeline agendado que combina arquivos, sinaliza dados ruins, recalcula fórmulas e entrega PDFs e pastas de trabalho protegidas. pandas, openpyxl e suas alternativas continuam sendo ótimas escolhas para análise e edições de tarefa única. Quando o trabalho se torna um fluxo de trabalho — vários formatos na entrada, resultados calculados na saída, PDFs e arquivos protegidos entregues em uma programação — uma API unificada de pasta de trabalho, com versão mantida e canal de suporte, é o que a sustenta em produção, e foi isso que os exemplos do Spire.XLS for Python neste guia demonstraram.
기본 편집을 넘어서는 Python Excel 자동화

매달 반복되는 동일한 Excel 작업이 있습니다. 지역별 판매 파일을 내려받아 마스터 통합 문서에 붙여 넣고, 합계를 새로 고치고, 잘못된 것으로 보이는 항목을 표시하고, PDF를 이메일로 보내고, 지난달 사본을 보관합니다. 어려운 작업은 하나도 없지만 바로 그것이 문제입니다. 이 작업은 반복적이고, 수작업으로 하면 오류가 발생하기 쉬우며, 파일 수가 늘어남에 따라 조용히 커집니다. Python Excel 자동화는 이러한 반복적인 수작업 단계를 일정에 따라 통합 문서를 읽고, 업데이트하고, 병합하고, 확인하고, 전달하는 스크립트로 대체합니다.
이 가이드는 다섯 줄짜리 셀 편집부터 수식을 다시 계산하고 PDF를 전달하는 예약된 파이프라인까지, 각 작업을 Spire.XLS for Python 16.8.2(PyPI의 독립 Python 패키지)로 구현한 방법을 보여 줍니다. 아래의 모든 코드 조각은 게시 전에 실제로 실행하고 출력 파일을 열어 검증했습니다. 또한 다른 일반적인 라이브러리가 어디에 적합한지도 언급하여 제품 소개서가 아닌 장단점을 확인할 수 있게 했습니다.
Excel 자동화를 위한 Python 라이브러리 선택
Python Excel 자동화는 작업이 일정에 따라 반복되고, 고정된 규칙을 따르며, 판단보다는 파일 처리를 포함할 때 적합합니다. 월간 보고서 작성, 주간 데이터 확인, 템플릿의 수치 업데이트, 다운스트림 시스템용 통합 문서 변환이 그 예입니다. 작업이 매번 형태가 바뀌거나 중간에 사람의 판단이 필요하다면 스크립트로 만드는 비용이 절약되는 것보다 더 클 것입니다. 범위에 대한 참고 사항 하나: 이 가이드는 Excel 파일 처리를 다룹니다. Excel에서 PowerPoint나 Word 문서를 생성하는 자동화는 관련은 있지만 별개의 주제입니다.
라이브러리 선택은 작업에 따라 달라집니다. 아래 표는 가장 접하게 될 다섯 가지 라이브러리를 요약한 것이며, 각 라이브러리는 전문 분야가 있으므로 한 줄로 정리했습니다.
| 라이브러리 | 적합한 용도 | 주요 고려 사항 |
|---|---|---|
| pandas | 표 형식 데이터 분석 및 변환 | 전체 통합 문서 개체 모델을 보존하지 않음 |
| openpyxl | 기존 XLSX/XLSM 통합 문서 편집 및 셀 수준 서식 지정 | 수식 계산 엔진 없음, 개체 지원 제한(다시 저장할 때 일부 도형 손실) |
| XlsxWriter | 서식과 차트가 포함된 새 XLSX 보고서 생성 | 기존 통합 문서를 읽거나 수정할 수 없음 |
| xlwings | 실행 중인 Excel 응용 프로그램 자동화 및 Python과 Excel 통합 | 클래식 에디션은 데스크톱 Excel 필요(PRO File Reader는 없이 Linux에서 실행 가능) |
| Spire.XLS | 통합 API를 통한 교차 형식 통합 문서 처리, 수식 계산 및 문서 변환 | 상용 라이선스, 지원 및 배포 조건은 요금제에 따라 다름 |
pandas는 이미 표에 맞는 분석에, openpyxl은 셀 수준 편집에, XlsxWriter는 새 통합 문서 작성에, xlwings는 Excel 자체를 구동하는 데 뒤지지 않습니다. 각각 워크플로의 다른 부분에 초점을 맞추고 있으며, 이들을 결합하면 추가 종속성과 서로 다른 개체 모델 간의 통합 작업이 필요합니다. Spire.XLS는 지원되는 형식 전반에 걸쳐 읽기, 편집, 계산, 변환, 보호를 아우르는 단일 API를 제공하므로 아래 예제는 모든 작업을 하나로 유지합니다.
구현 코드보다 라이브러리를 심층 비교하려면 Python용 최고의 Excel 라이브러리에서 비교 내용을 참조하세요.

Python으로 Excel 통합 문서 읽기 및 업데이트
가장 흔한 자동화 작업은 가장 간단한 작업이기도 합니다. 통합 문서를 불러오고, 일부 셀을 변경하고, 저장하는 것입니다. 먼저 pip install Spire.XLS로 패키지를 설치하면 전체 작업이 몇 줄 안에 끝납니다.
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("sales.xlsx") # load the template
ws = wb.Worksheets[0]
ws.Range["B2"].NumberValue = 150 # update an existing cell
ws.Range["A6"].Text = "Widget E" # append a new row
ws.Range["B6"].NumberValue = 45
ws.Range["C6"].NumberValue = 11.75
ws.Range["D6"].Formula = "=B6*C6" # formulas can be written
ws.Range["D6"].NumberFormat = "#,##0.00"
wb.SaveToFile("sales_updated.xlsx", FileFormat.Version2016)
wb.Dispose() # release the workbook
이를 기반으로 확장하기 전에 알아 두면 좋은 몇 가지 읽기 규칙이 있습니다. Spire.XLS의 API에서 Range[addr].NumberValue는 셀의 숫자 값을 반환하며 셀에 텍스트나 아무것도 없으면 NaN을 반환합니다. Range[addr].Text는 표시되는 문자열을 반환하고, 수식 셀의 경우 Range[addr].Formula는 수식 문자열을, FormulaNumberValue는 계산된 결과를 반환합니다. .Formula를 통해 수식을 작성하면 수식 자체가 저장됩니다. 계산된 결과를 파일에 유지하려면 이 가이드 뒤쪽의 재계산 섹션을 참조하세요.
이 코드 조각을 테스트한 결과, 업데이트된 값, 추가된 행, 해당 숫자 서식, 기존 헤더 스타일이 모두 저장 후에도 유지되었고 수식은 작성한 그대로 보존되었습니다. 저장된 파일을 Spire.XLS로 다시 열고 CalculateAllValue()를 호출하자 추가된 =B6*C6 셀에 대해 528.75가 반환되었으며, openpyxl을 통한 독립적인 읽기에서도 저장된 파일의 값이 동일하게 확인되었습니다.

Excel 보고서 자동화 및 일괄 처리
지역별 통합 문서를 하나의 마스터 보고서로 결합
지역 파일을 하나의 마스터 통합 문서로 결합하는 단계에서 자동화가 비용을 회수하기 시작합니다. Spire.XLS에서는 각 원본 파일을 차례로 불러오고, 할당된 범위를 통해 행을 읽으며, 데이터를 원본 열과 함께 새 통합 문서에 넣어 모든 행을 추적 가능하게 유지합니다.
import glob, os
from spire.xls import Workbook, FileFormat
master = Workbook()
ms = master.Worksheets[0]
ms.Range["A1"].Text = "Month"
ms.Range["B1"].Text = "Store"
ms.Range["C1"].Text = "Revenue"
ms.Range["D1"].Text = "Source File"
out_row = 2
for path in glob.glob("region_*.xlsx"):
wb = Workbook()
wb.LoadFromFile(path)
ws = wb.Worksheets[0]
for r in range(2, ws.AllocatedRange.RowCount + 1): # skip each file's header
for c in range(1, 4):
src = ws.Range[r, c]
nv = src.NumberValue
if not (isinstance(nv, float) and nv != nv): # NaN means "not a number"
ms.Range[out_row, c].NumberValue = nv
else:
ms.Range[out_row, c].Text = src.Value
ms.Range[out_row, 4].Text = os.path.basename(path)
out_row += 1
wb.Dispose()
master.SaveToFile("master_report.xlsx", FileFormat.Version2016)
master.Dispose()
입력 파일 3개로 테스트한 결과, 병합된 출력에는 입력 행의 합계와 정확히 일치하는 9개 행이 포함되었고, 수익 열에는 실제 숫자가 들어 있었으며(합계 94,298.00으로 입력과 센트 단위까지 일치), 원본 열에는 정확히 세 파일 이름이 기록되었고 헤더 행이 데이터에 섞여 들어가지 않았습니다. 결과는 openpyxl로도 다시 읽을 수 있었으므로 파이프라인의 다음 단계로 바로 넘길 수 있습니다. 주의할 경계 하나: 이 루프는 셀 값을 복사하며 원본 서식은 복사하지 않습니다. 원본 열에 실제 Excel 날짜, 백분율 또는 통화 값이 있다면 대상 열에 일치하는 숫자 서식을 적용하세요. 테스트 픽스처에서는 Month 열이 텍스트이므로 복사가 정확했습니다.

클라이언트별 서식 있는 보고서 생성
병합은 하나의 데이터 집합을 만들어 주고, 보고서 생성은 이를 전달물로 바꿉니다. 마스터 테이블을 읽고 클라이언트마다 서식 있는 인보이스 통합 문서를 하나씩 만드는 것은 반복 작업입니다. 행을 그룹화한 다음, 병합된 제목, 스타일이 지정된 헤더 행, 숫자 서식이 적용된 금액, SUM 합계로 각 인보이스를 만듭니다.
from spire.xls import Workbook, FileFormat, Color
wb = Workbook()
wb.LoadFromFile("invoice_master.xlsx")
ws = wb.Worksheets[0]
clients = {}
for r in range(2, ws.AllocatedRange.RowCount + 1):
client = ws.Range[r, 1].Value
clients.setdefault(client, []).append(
(ws.Range[r, 2].Value, ws.Range[r, 3].NumberValue))
for client, items in clients.items():
inv = Workbook()
sheet = inv.Worksheets[0]
sheet.Range["A1"].Text = f"Invoice - {client}"
sheet.Range["A1"].Style.Font.IsBold = True
sheet.Range["A1"].Style.Font.Size = 13
sheet.Range["A1:B1"].Merge()
sheet.Range["A3"].Text = "Service"
sheet.Range["B3"].Text = "Amount"
header = sheet.Range["A3:B3"]
header.Style.Color = Color.FromArgb(255, 68, 114, 196)
header.Style.Font.Color = Color.FromArgb(255, 255, 255, 255)
header.Style.Font.IsBold = True
row = 4
for service, amount in items:
sheet.Range[row, 1].Text = service
sheet.Range[row, 2].NumberValue = amount
sheet.Range[row, 2].NumberFormat = "#,##0.00"
row += 1
sheet.Range[row, 1].Text = "Total"
sheet.Range[row, 1].Style.Font.IsBold = True
sheet.Range[row, 2].Formula = f"=SUM(B4:B{row - 1})"
sheet.Range[row, 2].NumberFormat = "#,##0.00"
sheet.SetColumnWidth(1, 22)
sheet.SetColumnWidth(2, 14)
inv.SaveToFile(f"{client.replace(' ', '_').lower()}_invoice.xlsx",
FileFormat.Version2016)
inv.Dispose()
테스트에서 클라이언트 3곳이 3개의 통합 문서를 생성했고, 병합된 제목과 스타일이 지정된 헤더가 유지되었으며 =SUM 수식이 저장 후에도 남아 있었습니다. 실무 참고 사항 하나: 파일 이름은 클라이언트 이름에서 바로 만들어집니다. 실제 이름에 /나 : 같은 문자가 포함될 수 있다면 파일 이름을 만들기 전에 정리하세요. CalculateAllValue() 후 Acme 인보이스의 합계는 8,680.50으로 세 개의 품목과 정확히 일치했고 수식 문자열이 셀에 그대로 남아 있어 Excel이 열 때 계속 재계산합니다. 차트나 피벗 테이블이 있는 복잡한 템플릿의 경우 개체 보존 여부는 왕복 과정에서 시험됩니다. 이 내용은 아래 고급 섹션에서 다룹니다.
Excel 데이터 검증 및 예외 표시
자동화는 파일을 생산하는 것만이 아니라 확인하는 것이기도 합니다. 유용한 패턴은 통합 문서를 순회하며 데이터 품질 규칙을 적용하고, 규칙을 통과하지 못한 행을 표시하여 사람이 모든 내용을 다시 읽는 대신 플래그가 지정된 행만 검토하게 하는 검사 단계입니다. 이는 눈에 보이는 표시를 통한 데이터 확인이며, 사용자가 셀에 입력할 수 있는 내용을 제어하는 Excel의 데이터 유효성 검사 기능을 대체하지는 않습니다. Spire.XLS에서는 검사가 NumberValue를 통해 셀을 읽는데, 이는 텍스트와 빈 셀 모두에 대해 NaN을 반환하므로 아래 첫 번째 규칙은 두 경우를 구분하지 않고 missing_or_non_numeric으로 보고하며, 셀 스타일을 통해 실패를 표시합니다.
import math
from spire.xls import Workbook, FileFormat, Color
LIGHT_RED = Color.FromArgb(255, 254, 226, 226)
NOTE_RED = Color.FromArgb(255, 185, 28, 28)
wb = Workbook()
wb.LoadFromFile("payroll.xlsx")
ws = wb.Worksheets[0]
for row in range(2, ws.AllocatedRange.RowCount + 1):
salary = ws.Range[row, 2].NumberValue
bonus = ws.Range[row, 3].NumberValue
reasons = []
if math.isnan(salary) or math.isnan(bonus):
reasons.append("missing_or_non_numeric")
if not math.isnan(salary) and salary > 100000:
reasons.append("outlier")
if not math.isnan(bonus) and bonus < 0:
reasons.append("invalid")
if reasons:
ws.Range[row, 1, row, 3].Style.Color = LIGHT_RED
ws.Range[row, 4].Text = "; ".join(reasons)
ws.Range[row, 4].Style.Font.Color = NOTE_RED
wb.SaveToFile("qa_flagged.xlsx", FileFormat.Version2016)
wb.Dispose()
테스트 데이터에서 이 코드는 문제가 있는 4개 행(값이 없거나 숫자가 아닌 행 2개, 임계값을 초과한 급여 이상치 1개, 음수 보너스 1개)을 정확히 표시하고, 정상 행은 그대로 두었으며, D열에 행별 사유를 기록했는데 파일을 다시 열어 확인하고 기본 XML에서도 확인했습니다. 변경되지 않은 테스트 통합 문서에서 검사를 다시 실행해도 동일한 4개 행이 표시되었습니다. 여기의 규칙은 의도적으로 단순합니다. 실제 급여 데이터의 경우 임계값과 규칙 집합이 핵심이며, 이는 버전 관리와 검토가 가능한 코드에 있습니다.

이 패턴은 이전 섹션과 잘 어울립니다. 지역 파일을 병합하고, 결합된 데이터를 검사한 뒤, 검사 결과에 따라 통합 문서를 검토 또는 전달로 라우팅할 수 있습니다.
Python Excel 자동화 예약
직접 실행해야 하는 스크립트는 자동화의 절반에 불과합니다. 나머지 절반은 스크립트가 정해진 시간에 실행되도록 하는 것입니다. 위 단계들은 순수 Python이므로 완성된 워크플로(불러오기, 병합, 검사, 생성, 전달)를 하나의 함수로 묶어 운영 체제 스케줄러가 단독으로 실행하게 할 수 있습니다.
| 방법 | 실행 방식 | 적합한 용도 |
|---|---|---|
| Windows 작업 스케줄러 | 운영 체제가 Python 스크립트를 시작 | Windows의 반복 보고서 |
| cron | 운영 체제가 Linux/macOS에서 스크립트를 시작 | 서버 측 예약 작업 |
둘 다 스크립트를 시작하고, 작업을 수행하게 한 뒤 종료하므로 계속 관리해야 할 장기 실행 프로세스가 없습니다. 다만 누락된 실행에 대한 동작은 다릅니다. Windows 작업 스케줄러는 예약된 시작 시간을 놓친 경우 가능한 한 빨리 작업을 실행하도록 구성할 수 있지만, 표준 cron 작업은 일반적으로 시스템이 오프라인인 동안 누락된 실행을 따라잡지 않습니다. 나중에 혼란을 줄여 주는 배포 참고 사항: Spire.XLS는 통합 문서 파일을 직접 처리하며 데스크톱 Excel을 설치할 필요가 없으므로 위 스크립트는 Linux 서버나 컨테이너에서 실행됩니다. 이는 COM 자동화를 통해 데스크톱 Office를 스크립팅하던 이전 방식을 대체합니다. 그러나 Excel이 필요 없다는 것이 Excel의 모든 동작을 재현한다는 뜻은 아닙니다. 다음 섹션에서는 실제로 재현하기 어려운 부분을 다룹니다.
고급 Excel 자동화 작업 처리
많은 파이프라인에서 위 섹션들이 최종 답입니다. 일부 워크플로는 더 많은 입력 형식, 반드시 다시 계산해야 하는 수식, PDF 전달, 보호된 아카이브 등 요구 사항을 계속 추가합니다. 이 섹션에서는 Spire.XLS for Python 16.8.2(PyPI의 독립 Python 패키지)로 테스트한 코드를 통해 이러한 지점을 살펴봅니다. 이는 더 어려운 요구 사항에 대한 하나의 구현 경로이며, 이 페이지의 모든 작업에 대한 기본 답은 아닙니다.
여러 파일 형식 작업
업스트림 시스템이 .xls, .xlsb, .ods를 내보내는데 파이프라인은 .xlsx를 기대하는 경우가 흔합니다. 각 형식은 보통 서로 다른 Python 패키지와 엔진을 의미합니다. Spire.XLS는 동일한 통합 문서 API를 통해 이를 처리합니다. 16.8.2로 테스트한 결과, 동일한 통합 문서 개체가 .xls, .ods, .xlsx, .xlsb(FileFormat.Xlsb2007 / Xlsb2010)를 불러오고 저장했으며, .xls, .ods, .xlsb를 값이 그대로 유지된 채 자체 형식으로 왕복 변환했습니다. 작성한 .xlsb 파일도 Excel에서 문제없이 다시 열렸지만, 오픈 소스 pyxlsb 파서는 이를 읽을 수 없었으므로 실제로 사용하기 전에 자체 다운스트림 리더로 확인할 가치가 있습니다.
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("legacy_input.xls") # also reads .xlsb and .ods
wb.SaveToFile("converted.xlsx", FileFormat.Version2016)
wb.Dispose()
구분해 둘 만한 차이 하나: "원래 형식으로 편집하고 다시 저장"하는 것과 "전달을 위해 변환"하는 것은 서로 다른 목표입니다. 전자는 작업 파일을 제자리에 유지하고, 후자는 다운스트림 소비자에게 공급합니다. 둘 다 아래의 엔드투엔드 예제에 나옵니다.
수식 재계산
수식을 작성하는 라이브러리가 반드시 결과도 작성하는 것은 아닙니다. 예를 들어 openpyxl은 수식 문자열을 보존하지만 계산된 값을 저장하지 않으므로, 계산하지 않는 다운스트림 리더는 아무것도 보지 못합니다. 이는 예약된 파이프라인이 파일을 그대로 읽는 시스템에 파일을 전달할 때 실제 문제입니다.
계산 엔진이 이 간극을 메웁니다.
from spire.xls import Workbook, FileFormat
wb = Workbook()
wb.LoadFromFile("model.xlsx") # formulas written by another tool, no cached values
wb.CalculateAllValue() # compute every formula
wb.SaveToFile("model_calculated.xlsx", FileFormat.Version2016)
wb.Dispose()
이를 양쪽에서 검증했습니다. 불러올 때 Spire.XLS는 기본적으로 메모리에서 이미 계산하므로(RecalculateOnOpen이 켜져 있음) FormulaNumberValue는 계산된 숫자를 즉시 읽습니다. 그러나 결과를 파일에 유지하려면 저장 전에 명시적으로 CalculateAllValue()를 호출해야 합니다. 호출하면 저장된 파일에 계산된 값이 포함되었고 data_only=True로 읽은 openpyxl 리더에서도 이를 확인했습니다. 호출하지 않으면 같은 셀이 None으로 읽힙니다. 그 저장 후에는 어떤 라이브러리든 결과를 읽을 수 있습니다. 명확히 할 경계 하나: 계산은 엔진이 지원하는 함수와 종속성을 대상으로 합니다. 외부 링크, 추가 기능 함수 또는 지원되지 않는 함수 집합에 의존하는 통합 문서는 계산된 출력에 의존하기 전에 자체 파일로 테스트해야 합니다.

Excel 보고서를 PDF로 내보내기
예약된 보고서는 보통 통합 문서를 열지 않는 사람을 위해 PDF로 끝납니다. 열 너비, 글꼴, 차트 등을 포함해 스프레드시트를 충실히 렌더링하는 것이 바로 일반 변환 도구가 잘못하는 부분입니다. Spire.XLS에서는 페이지 설정을 먼저 정의한 뒤 워크시트가 스스로 렌더링됩니다.
from spire.xls import Workbook, PageOrientationType
wb = Workbook()
wb.LoadFromFile("model_calculated.xlsx")
sheet = wb.Worksheets[0]
sheet.PageSetup.Orientation = PageOrientationType.Portrait
sheet.PageSetup.FitToPagesWide = 1
sheet.PageSetup.FitToPagesTall = 1
sheet.SaveToPdf("report.pdf") # worksheet-level export
wb.Dispose()
FitToPagesWide와 FitToPagesTall 설정은 워크시트를 가로 1페이지, 세로 1페이지 안에 맞게 축소하여 열이 페이지에 걸쳐 나뉘지 않게 합니다. 다만 매우 넓은 시트에서는 축소된 텍스트가 편하게 읽기 어려울 만큼 작아질 수 있습니다. 워크시트 수준의 SaveToPdf는 통합 문서의 모든 워크시트가 아니라 선택한 시트만 정확히 내보냅니다. 테스트에서 내보낸 PDF는 제목, 재계산된 합계를 포함한 전체 표, 렌더링된 차트가 있는 한 페이지로 나왔습니다. 레이아웃 세부 정보는 Python에서 Excel을 PDF로 변환을 참조하세요.

차트 및 피벗 테이블 작업
보고서 통합 문서에는 보통 셀뿐 아니라 개체도 포함됩니다. 테스트 통합 문서에서 Spire.XLS 16.8.2를 통한 왕복 변환은 XML 수준에서 차트 파트를 그대로 유지했고, 파일을 Excel에서 다시 열었을 때 차트가 완전히 렌더링되었습니다. 이는 테스트 픽스처에 대한 결과이며 모든 DrawingML 개체에 대한 보장은 아닙니다. 복잡한 도형은 모든 라이브러리에 적용되는 조언과 마찬가지로 자체 파일로 확인해야 합니다. Spire.XLS의 통합 문서 API는 피벗 테이블과 피벗 차트도 다룹니다(생성, 새로 고침, 필드 작업). 피벗 테이블 쪽은 Excel에서 피벗 테이블 생성 또는 조작을 참조하세요. 테스트 픽스처에는 피벗 테이블이 없었으므로 실제로 사용하기 전에 자체 통합 문서로 왕복 테스트를 실행하세요.
Excel 통합 문서 보호
보관되거나 이메일로 전송되는 보고서에는 열기 암호가 필요한 경우가 많습니다. 호출 한 번으로 설정할 수 있습니다.
wb.Protect("Report2026")
wb.SaveToFile("protected_report.xlsx", FileFormat.Version2016)
wb.Dispose()
테스트에서 해당 파일은 암호 없이는 열리지 않았으며, 암호화된 컨테이너에서 오류를 발생시킨 openpyxl에서도 마찬가지였습니다. 같은 라이브러리로 다시 읽으려면 OpenPassword 속성이 필요합니다. 따라서 파이프라인이 파일을 보호하고 나중에 보호된 파일을 다시 읽는다면 도구 체인의 리더 측에서도 이를 지원해야 합니다.
프로덕션 Excel 자동화를 위한 라이브러리 선택
API 범위 외에도 프로덕션 종속성에는 유지 관리 계획이 필요합니다. Spire.XLS for Python은 계속 릴리스되고 있습니다. 예를 들어 16.8.2(2026년 8월, 이 가이드 전체에서 테스트한 릴리스)는 TEXTSPLIT 수식 지원을 추가했습니다. 라이선스는 영구적입니다. 라이선스는 약관에 따라 계속 사용을 보장하며, 새 릴리스에 대한 액세스는 업데이트 자격을 따릅니다. 라이선스 요금제에는 1년간의 제품 업데이트 및 핫픽스가 포함되며, 상용 지원은 커뮤니티 추적기 대신 형식, 계산 또는 변환 문제에 대해 정의된 공급업체 채널을 제공합니다. 응답 시간 목표, 지원 채널 및 요금제별 추가 기능은 등급에 따라 다릅니다. Spire.XLS for Python 라이선스 요금제 페이지 또는 개발자 수와 배포 범위가 선택에 어떻게 맞는지에 대한 Python용 최고의 Excel 라이브러리 비교를 참조하세요.
엔드투엔드 예제
위의 조각들은 하나의 변환-전달 워크플로로 결합됩니다. 레거시 .xlsb 입력을 읽고, 수치를 업데이트하고, 다시 계산한 뒤, PDF와 암호로 보호된 .xlsx를 모두 전달합니다.
from spire.xls import Workbook, FileFormat, PageOrientationType
wb = Workbook()
wb.LoadFromFile("monthly_input.xlsb") # read the binary format
sheet = wb.Worksheets[0]
sheet.Range["B2"].NumberValue = 125000 # update an input cell
wb.CalculateAllValue() # persist computed results
sheet.PageSetup.Orientation = PageOrientationType.Portrait
sheet.PageSetup.FitToPagesWide = 1
sheet.PageSetup.FitToPagesTall = 1
sheet.SaveToPdf("monthly_report.pdf") # deliverable 1: PDF
wb.Protect("Report2026") # deliverable 2: protected xlsx
wb.SaveToFile("monthly_report.xlsx", FileFormat.Version2016)
wb.Dispose() # release the workbook

모든 단계는 Spire.XLS for Python 16.8.2와 Python 3.13을 사용한 테스트 환경에서 검증되었습니다. 이 워크플로가 요구 사항과 일치한다면 Spire.XLS for Python을 살펴보세요. 무료 에디션은 기본 평가에 충분합니다. 상용 프로젝트의 경우 1개월 임시 라이선스를 요청하고 자체 통합 문서로 전체 API를 테스트한 후 프로덕션 라이선스를 선택하세요(현재 약관은 공식 페이지에서 확인).
자주 묻는 질문
Excel이 설치되지 않은 상태에서 Python으로 Excel을 자동화할 수 있나요?
파일 처리의 경우 가능합니다. Spire.XLS는 통합 문서 파일을 직접 읽고 쓰며, 여기의 예제 중 데스크톱 Excel이 필요했던 것은 없습니다. 예외는 실행 중인 Excel 응용 프로그램을 구동하는 xlwings Classic입니다. "Excel이 필요 없음"은 코드 실행에 관한 것이지 모든 Excel 동작을 재현한다는 뜻은 아닙니다.
Excel 자동화에 가장 적합한 Python 라이브러리는 무엇인가요?
작업에 따라 다릅니다. 분석에는 pandas, 셀 수준 .xlsx 편집에는 openpyxl, 새 서식 통합 문서에는 XlsxWriter, Excel 자체 구동에는 xlwings가 적합합니다. 읽기, 편집, 계산, 변환, 보호를 아우르는 단일 API는 Python용 최고의 Excel 라이브러리 비교를 참조하세요.
openpyxl로 Excel 수식을 다시 계산할 수 있나요?
아니요. openpyxl은 수식 문자열을 보존하지만 계산 엔진이 없으며, openpyxl로 작성한 수식에는 캐시된 결과가 없습니다. data_only=True는 파일에 저장된 캐시만 읽으므로 해당 셀에 대해서는 None을 읽습니다. 결과를 계산하고 유지하려면 Excel에서 수식 추가 또는 읽기를 참조하세요.
Python Excel 스크립트를 어떻게 예약하나요?
Windows 작업 스케줄러나 cron을 사용하여 운영 체제가 스크립트를 시작하게 하세요. 작업 스케줄러는 누락된 작업을 다시 실행하도록 설정할 수 있지만, 표준 cron은 시스템이 오프라인인 동안 누락된 실행을 따라잡지 않습니다. 스크립트가 통합 문서 파일을 직접 처리하므로 실행하는 시스템에 데스크톱 Excel이 필요하지 않습니다.
Python으로 Excel을 PDF로 어떻게 변환하나요?
페이지 설정(방향, 페이지 맞춤)을 지정하고 PDF를 자체적으로 렌더링하는 라이브러리로 워크시트를 직접 내보내세요. 오픈 소스 경로는 레이아웃을 직접 처리해야 하는 별도의 변환 라이브러리가 필요합니다. 자세한 내용은 Python에서 Excel을 PDF로 변환을 참조하세요.
결론
Python Excel 자동화는 다섯 줄짜리 셀 편집부터 파일을 병합하고, 잘못된 데이터를 표시하고, 수식을 다시 계산하고, PDF와 보호된 통합 문서를 전달하는 예약된 파이프라인까지 아우릅니다. pandas, openpyxl 및 그 주변 라이브러리는 분석과 단일 작업 편집에 여전히 강력한 선택입니다. 작업이 워크플로(여러 형식 입력, 계산된 결과 출력, 일정에 따른 PDF 및 보호된 아카이브 전달)가 되면 유지 관리되는 릴리스와 지원 채널을 갖춘 통합 통합 문서 API가 프로덕션에서 이를 뒷받침하며, 이 가이드의 Spire.XLS for Python 예제가 보여 준 것이 바로 그것입니다.