File Word chứa văn bản định dạng trong 3 cấp: Run (cấp thấp), Paragraph (cấp trung), Document (cấp cao). Không thể chỉnh sửa bằng trình soạn thảo văn bản thường. Python dùng module python-docx để thao tác.
Cài đặt và sử dụng
- Cài đặt:
pip install python-docx - Import:
import docx(KHÔNG phải python-docx) - Sử dụng
docx.Document()để tạo/mở tài liệu.
Ví dụ
import docx
# Tạo document mới
doc = docx.Document()
# Thêm tiêu đề cấp 0 (lớn nhất)
doc.add_heading('Heading for the document', 0)
# Thêm đoạn văn
doc_para = doc.add_paragraph('Your paragraph goes here, ')
# Thêm run (đoạn văn bản có định dạng)
doc_para.add_run('hey there, bold here').bold = True
doc_para.add_run(', and ')
doc_para.add_run('these words are italic').italic = True
# Ngắt trang
doc.add_page_break()
# Tiêu đề cấp 2
doc.add_heading('Heading level 2', 2)
# Thêm hình ảnh (width tùy chọn)
doc.add_picture('path_to_picture')
# Lưu file
doc.save('path_to_document')Các thao tác phổ biến
add_heading(text, level): level 0-9.add_paragraph(): thêm đoạn văn.run.bold,run.italic,run.underline: định dạng.add_picture(): chèn ảnh.add_table(): tạo bảng.