最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Python自動化實現(xiàn)Word文檔專業(yè)排版

 更新時間:2026年05月22日 08:51:07   作者:劉子毅  
在辦公自動化領(lǐng)域,用 Python 處理 Word 文檔已經(jīng)是非常成熟和高效的方案了,本文將和大家使用Python實現(xiàn)自動化Word文檔排版的相關(guān)知識,希望對大家有所幫助

在辦公自動化領(lǐng)域,用 Python 處理 Word 文檔已經(jīng)是非常成熟和高效的方案了。通過幾個核心庫的配合使用,完全可以實現(xiàn)從文檔生成、批量處理到專業(yè)排版的全流程自動化。

核心庫選型與對比

在開始寫代碼之前,需要了解目前 Python 生態(tài)中幾個主流的 Word 處理庫,根據(jù)實際需求選擇合適的工具組合。

庫名稱定位核心能力適用場景
python-docx基礎(chǔ)操作庫創(chuàng)建/讀取 .docx,添加段落、表格、圖片、頁眉頁腳,設(shè)置基礎(chǔ)樣式日常辦公自動化,入門首選
docxtpl模板引擎基于 Jinja2 語法,支持變量、循環(huán)、條件判斷,模板與數(shù)據(jù)分離批量生成合同、報告、證書
Spire.Doc專業(yè)商業(yè)庫全格式支持(.doc/.docx),高級排版,高精度轉(zhuǎn)換企業(yè)級文檔處理需求
Aspose.Words企業(yè)級商業(yè)庫完整文檔生命周期管理,超強格式保真度專業(yè)文檔管理系統(tǒng)
python-docx-templatepython-docx 擴展在 python-docx 基礎(chǔ)上增強模板功能需要 python-docx 原生能力的模板場景

環(huán)境搭建

pip install python-docx
pip install docxtpl
pip install openpyxl pandas  # 用于數(shù)據(jù)讀取
pip install Pillow           # 圖片處理

建議使用虛擬環(huán)境管理依賴,避免版本沖突。

核心功能實現(xiàn)

創(chuàng)建文檔與段落操作

這是最基礎(chǔ)的文檔生成方式,下面代碼展示了創(chuàng)建文檔、添加各級標(biāo)題、設(shè)置段落對齊和字體格式的完整流程。

from docx import Document
from docx.shared import Pt, RGBColor, Inches
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
def create_basic_document():
    """創(chuàng)建基礎(chǔ)文檔"""
    doc = Document()
    # 添加標(biāo)題(0級標(biāo)題,類似大標(biāo)題)
    doc.add_heading('Python自動化排版工具', level=0)
    # 添加一級標(biāo)題
    doc.add_heading('第一章 引言', level=1)
    # 添加二級標(biāo)題
    doc.add_heading('1.1 背景介紹', level=2)
    # 添加段落并設(shè)置格式
    para = doc.add_paragraph()
    run = para.add_run('這是使用Python自動生成的第一個段落。')
    run.font.size = Pt(12)
    run.font.name = '宋體'
    run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋體')  # 解決中文顯示問題
    # 居中對齊示例
    center_para = doc.add_paragraph()
    center_run = center_para.add_run('居中對齊標(biāo)題')
    center_run.font.size = Pt(14)
    center_run.font.bold = True
    center_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    # 設(shè)置段落縮進(jìn)和行距
    from docx.shared import Cm
    indent_para = doc.add_paragraph('這是一個設(shè)置了首行縮進(jìn)和段前間距的段落,用于展示專業(yè)排版效果。')
    indent_para.paragraph_format.first_line_indent = Cm(0.75)  # 首行縮進(jìn)
    indent_para.paragraph_format.space_before = Pt(12)         # 段前間距
    indent_para.paragraph_format.space_after = Pt(6)           # 段后間距
    doc.save('basic_document.docx')
    print("基礎(chǔ)文檔創(chuàng)建完成!")
create_basic_document()

關(guān)鍵知識點

  • doc.add_heading(level=x) 中 level 的范圍是 0~9,0 為文檔主標(biāo)題,1~9 對應(yīng)各級標(biāo)題。
  • 設(shè)置中文字體時,需要同時設(shè)置 run.font.name 和 run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋體'),否則中文可能顯示異常。
  • 段落間距的單位可以使用 Pt(磅)、Cm(厘米)等。

表格操作(Excel 數(shù)據(jù)導(dǎo)入)

表格是 Word 文檔中常用的元素,結(jié)合 pandas 可以輕松實現(xiàn) Excel 數(shù)據(jù)導(dǎo)入到 Word 表格。

from docx import Document
from docx.shared import Pt, RGBColor
from docx.oxml.ns import qn
import pandas as pd

def create_sales_report_table():
    """創(chuàng)建銷售報告表格"""
    doc = Document()
    doc.add_heading('2026年第一季度銷售報告', level=0)
    
    # 從 Excel 讀取數(shù)據(jù)(實際使用時可替換為真實文件路徑)
    # df = pd.read_excel('sales_data.xlsx')
    # 這里用示例數(shù)據(jù)代替
    data = {
        '產(chǎn)品名稱': ['智能手表A', '降噪耳機B', '無線充電器C', '運動手環(huán)D'],
        '1月銷量': [1250, 980, 2100, 1560],
        '2月銷量': [1420, 1050, 2350, 1680],
        '3月銷量': [1680, 1180, 2580, 1820]
    }
    df = pd.DataFrame(data)
    
    # 創(chuàng)建表格(行數(shù) = 數(shù)據(jù)行數(shù) + 標(biāo)題行)
    table = doc.add_table(rows=len(df) + 1, cols=len(df.columns))
    table.style = 'Table Grid'  # 應(yīng)用網(wǎng)格樣式
    
    # 設(shè)置表頭
    header_cells = table.rows[0].cells
    for i, col_name in enumerate(df.columns):
        header_cells[i].text = col_name
        # 設(shè)置表頭格式
        run = header_cells[i].paragraphs[0].runs[0]
        run.font.bold = True
        run.font.size = Pt(11)
        run.font.name = '微軟雅黑'
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '微軟雅黑')
    
    # 填充數(shù)據(jù)
    for idx, row in df.iterrows():
        row_cells = table.rows[idx + 1].cells
        for col_idx, value in enumerate(row):
            row_cells[col_idx].text = str(value)
    
    # 調(diào)整列寬
    for col_idx in range(len(df.columns)):
        table.columns[col_idx].width = Cm(3) if col_idx == 0 else Cm(2)
    
    doc.save('sales_report.docx')
    print("銷售報告生成完成!")
    
create_sales_report_table()

實際項目中,如果不需要整表創(chuàng)建,也可以使用 doc.add_table(rows=1, cols=3) 配合 add_row() 動態(tài)追加數(shù)據(jù)的方式。但使用 pandas 配合上述代碼可以更靈活地處理來源 Excel 數(shù)據(jù)。

圖文混排與圖片控制

插入帶題注的圖片并自動居中是專業(yè)排版中的常見需求,下面代碼實現(xiàn)了自動居中并添加題注編號。

from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
import os

def insert_image_with_caption(doc, img_path, caption_text):
    """插入帶題注的圖片,自動居中并編號"""
    # 插入圖片段落并居中
    para = doc.add_paragraph()
    run = para.add_run()
    run.add_picture(img_path, width=Inches(4.5))
    para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    
    # 獲取當(dāng)前圖片序號
    pic_count = len(doc.inline_shapes)
    # 添加題注
    caption = doc.add_paragraph(f'圖{pic_count} {caption_text}')
    caption.style = 'Caption'
    caption.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    
    # 設(shè)置題注字體
    for run in caption.runs:
        run.font.size = Pt(10)
        run.font.name = '宋體'
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋體')

def create_picture_document():
    """創(chuàng)建圖文混排文檔"""
    doc = Document()
    doc.add_heading('產(chǎn)品技術(shù)白皮書', level=0)
    
    doc.add_heading('第二章 產(chǎn)品設(shè)計', level=1)
    doc.add_paragraph('本章節(jié)展示了產(chǎn)品的整體設(shè)計架構(gòu)和技術(shù)優(yōu)勢。')
    
    # 插入圖片(請?zhí)鎿Q為實際圖片路徑)
    # insert_image_with_caption(doc, 'architecture.png', '產(chǎn)品架構(gòu)圖')
    
    doc.add_paragraph('從上圖可以看出,本產(chǎn)品采用了模塊化設(shè)計,各模塊之間通過標(biāo)準(zhǔn)化接口通信。')
    doc.add_paragraph('這一設(shè)計理念帶來了以下優(yōu)勢:')
    
    # 添加列表
    ul = doc.add_paragraph()
    for item in ['可擴展性強', '維護成本低', '開發(fā)效率高']:
        ul.add_run(f'? {item}\n')
    
    doc.save('technical_report.docx')
    print("技術(shù)白皮書生成完成!")
    
create_picture_document()

使用 add_picture 時,可以通過 width 和 height 參數(shù)精確控制圖片尺寸。

專業(yè)排版技巧

樣式模板應(yīng)用

通過 doc.styles 管理樣式可以實現(xiàn)全局格式統(tǒng)一,避免重復(fù)設(shè)置。

from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn

def apply_unified_styles():
    """應(yīng)用統(tǒng)一樣式模板"""
    doc = Document()
    
    # 獲取并修改標(biāo)題樣式
    heading1_style = doc.styles['Heading 1']
    heading1_style.font.size = Pt(18)
    heading1_style.font.bold = True
    heading1_style.font.name = '黑體'
    heading1_style._element.rPr.rFonts.set(qn('w:eastAsia'), '黑體')
    heading1_style.paragraph_format.space_before = Pt(18)
    heading1_style.paragraph_format.space_after = Pt(12)
    
    # 修改正文樣式
    normal_style = doc.styles['Normal']
    normal_style.font.size = Pt(11)
    normal_style.font.name = '宋體'
    normal_style._element.rPr.rFonts.set(qn('w:eastAsia'), '宋體')
    normal_style.paragraph_format.first_line_indent = Cm(0.75)
    normal_style.paragraph_format.line_spacing = 1.5
    
    # 創(chuàng)建自定義樣式
    custom_style = doc.styles.add_style('Custom Note', 1)  # 1 表示段落樣式
    custom_style.font.size = Pt(10)
    custom_style.font.color.rgb = RGBColor(100, 100, 100)
    custom_style.font.italic = True
    custom_style.paragraph_format.space_before = Pt(6)
    
    # 使用樣式
    doc.add_heading('第一章 項目概述', level=1)
    doc.add_paragraph('這是應(yīng)用統(tǒng)一樣式后的正文內(nèi)容,所有格式將保持一致。')
    
    note_para = doc.add_paragraph('【注釋】此處為自定義樣式展示', style='Custom Note')
    
    doc.save('styled_document.docx')
    print("樣式文檔生成完成!")
    
apply_unified_styles()

樣式修改的核心要點是修改樣式定義而非逐個元素設(shè)置,這樣后期需要調(diào)整格式時只需修改樣式定義,所有應(yīng)用該樣式的內(nèi)容會自動更新。

頁眉頁腳與頁碼

頁眉頁腳操作可以通過 section 對象輕松獲取,頁碼的添加則需要通過底層 XML 實現(xiàn)。

from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

def add_header_footer_with_pagination():
    """添加頁眉頁腳和頁碼"""
    doc = Document()
    
    # 獲取第一個節(jié)的頁眉
    section = doc.sections[0]
    header = section.header
    header_para = header.paragraphs[0]
    header_para.text = "技術(shù)報告 | 機密文檔"
    header_para.alignment = 1  # 居中
    
    # 添加頁腳和頁碼
    footer = section.footer
    footer_para = footer.paragraphs[0]
    footer_para.alignment = 1  # 居中
    
    # 通過底層 XML 添加頁碼字段
    run = footer_para.add_run()
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'begin')
    run._r.append(fldChar)
    
    instrText = OxmlElement('w:instrText')
    instrText.text = "PAGE"
    run._r.append(instrText)
    
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'end')
    run._r.append(fldChar)
    
    run.add_text(" / ")
    
    run = footer_para.add_run()
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'begin')
    run._r.append(fldChar)
    
    instrText = OxmlElement('w:instrText')
    instrText.text = "NUMPAGES"
    run._r.append(instrText)
    
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'end')
    run._r.append(fldChar)
    
    # 添加文檔內(nèi)容
    for i in range(1, 6):
        doc.add_heading(f'第{i}章 內(nèi)容章節(jié)', level=1)
        doc.add_paragraph(f'這是第{i}章的具體內(nèi)容,文檔將自動生成頁碼。')
        doc.add_page_break()
    
    doc.save('document_with_pagination.docx')
    print("帶頁碼文檔生成完成!")
    
add_header_footer_with_pagination()

頁碼字段(field)不是普通文本,而是 Word 的動態(tài)字段,需要通過 OOXML 的字段元素來構(gòu)造。

自動生成目錄

目錄生成需要理解 Word 中目錄字段的工作原理,通過插入 TOC 字段實現(xiàn)。

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def add_auto_table_of_contents():
    """添加自動目錄"""
    doc = Document()
    
    # 插入目錄
    doc.add_heading('文檔目錄', level=0)
    
    # 插入 TOC 字段
    paragraph = doc.add_paragraph()
    run = paragraph.add_run()
    
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'begin')
    run._r.append(fldChar)
    
    instrText = OxmlElement('w:instrText')
    instrText.text = 'TOC \\o "1-3" \\h \\z \\u'
    run._r.append(instrText)
    
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'end')
    run._r.append(fldChar)
    
    # 添加章節(jié)內(nèi)容
    for i in range(1, 5):
        doc.add_heading(f'第{i}章 主要內(nèi)容', level=1)
        for j in range(1, 4):
            doc.add_heading(f'{i}.{j} 小節(jié)內(nèi)容', level=2)
            doc.add_paragraph('這是小節(jié)的具體內(nèi)容描述,目錄會自動捕捉并顯示。')
        doc.add_page_break()
    
    doc.save('document_with_toc.docx')
    print("帶自動目錄的文檔生成完成!")
    
add_auto_table_of_contents()

目錄字段 \o "1-3" 的含義是包含級別 1-3 的標(biāo)題,\h 表示超級鏈接,\z 表示隱藏標(biāo)簽,\u 表示使用段落大綱級別。

高級排版功能

分節(jié)與頁面設(shè)置

分節(jié)是 Word 排版中的高級功能,允許在同一文檔中設(shè)置不同的頁面布局。

from docx import Document
from docx.shared import Cm
from docx.enum.section import WD_SECTION

def add_section_and_layout():
    """分節(jié)與頁面設(shè)置"""
    doc = Document()
    
    # 獲取文檔的第一節(jié)
    section = doc.sections[0]
    
    # 設(shè)置頁面邊距
    section.top_margin = Cm(2.54)
    section.bottom_margin = Cm(2.54)
    section.left_margin = Cm(3.17)
    section.right_margin = Cm(3.17)
    
    # 添加文檔內(nèi)容
    doc.add_heading('報告正文', level=1)
    doc.add_paragraph('這是報告正文的第一頁內(nèi)容,使用標(biāo)準(zhǔn)頁邊距設(shè)置。')
    doc.add_page_break()
    
    # 添加新節(jié)
    new_section = doc.add_section(WD_SECTION.NEW_PAGE)
    
    # 為新節(jié)設(shè)置不同的頁邊距(方便插入寬表格)
    new_section.top_margin = Cm(2.0)
    new_section.bottom_margin = Cm(2.0)
    new_section.left_margin = Cm(1.5)
    new_section.right_margin = Cm(1.5)
    
    doc.add_heading('附錄', level=1)
    doc.add_paragraph('附錄部分使用更寬的頁面邊距,便于展示大型表格和圖表。')
    
    doc.save('document_with_sections.docx')
    print("分節(jié)文檔生成完成!")
    
add_section_and_layout()

中文排版優(yōu)化(字體與編碼)

處理中文文檔時,字體設(shè)置和編碼處理是兩個最常見的坑。通過以下函數(shù)可以系統(tǒng)性地解決這些問題。

from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn

def optimize_chinese_document():
    """優(yōu)化中文文檔排版"""
    doc = Document()
    
    # 統(tǒng)一設(shè)置全局中文字體
    def set_chinese_font(run, font_name='宋體', font_size=12):
        run.font.name = font_name
        run.font.size = Pt(font_size)
        run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
    
    # 添加標(biāo)題
    title = doc.add_heading('中文文檔排版優(yōu)化指南', level=0)
    for run in title.runs:
        run.font.name = '黑體'
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '黑體')
        run.font.size = Pt(22)
    
    # 添加正文內(nèi)容
    para = doc.add_paragraph()
    run = para.add_run('這是一段經(jīng)過優(yōu)化后的中文文檔內(nèi)容,字體顯示正常,段落格式專業(yè)。')
    set_chinese_font(run, '宋體', 12)
    
    # 設(shè)置段落首行縮進(jìn)
    para.paragraph_format.first_line_indent = Cm(0.75)
    
    doc.save('optimized_chinese_doc.docx')
    print("中文優(yōu)化文檔生成完成!")
    
optimize_chinese_document()

中文字體設(shè)置的根本原因是 python-docx 默認(rèn)的英文字體不支持中文,需要通過修改 XML 中的 w:eastAsia 屬性來指定中文字體,兩者是獨立設(shè)置的。

知識擴展

下面分享了一個基于Python開發(fā)的word文檔專業(yè)排版工具,完整代碼如下:

import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from docx import Document
from docx.shared import Pt, Cm
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
import os
import re
import sys
# --- 1. 環(huán)境檢測與 .doc 轉(zhuǎn)換模塊 (僅Windows有效) ---
if sys.platform.startswith('win'):
    try:
        import win32com.client
        CONVERT_ENABLED = True
    except ImportError:
        CONVERT_ENABLED = False
        print("提示: 如需處理 .doc 文件,請安裝 pywin32: pip install pywin32")
else:
    CONVERT_ENABLED = False
def convert_doc_to_docx(doc_path):
    """將舊版 .doc 轉(zhuǎn)換為 .docx"""
    if not CONVERT_ENABLED:
        return False, "非Windows環(huán)境,無法轉(zhuǎn)換 .doc 文件"
    word = None
    try:
        # 優(yōu)先嘗試 WPS
        word = win32com.client.Dispatch("Kwps.Application")
    except:
        try:
            # 備選嘗試 Office
            word = win32com.client.Dispatch("Word.Application")
        except:
            return False, "未檢測到WPS或Office軟件"
    try:
        doc = word.Documents.Open(doc_path)
        docx_path = doc_path + "x"
        # WPS和Office通用的保存格式代碼 (wdFormatXMLDocument)
        doc.SaveAs(docx_path, 12) 
        doc.Close()
        word.Quit()
        return True, docx_path
    except Exception as e:
        if word: word.Quit()
        return False, f"轉(zhuǎn)換失敗: {str(e)}"
# --- 2. 核心配置 (初始化默認(rèn)值) ---
CONFIG = {
    "margin": (2.54, 2.54, 3.17, 3.17),
    "western_font": "Times New Roman",
    "line_height": Pt(28.95),
    "line_rule": WD_LINE_SPACING.EXACTLY,
    "fonts": {
        "title": "方正小標(biāo)宋_GBK",
        "heading_1": "黑體",
        "heading_2": "楷體_GB2312",
        "heading_3": "仿宋_GB2312",
        "body": "仿宋_GB2312"
    },
    "font_sizes": {
        "title": 22,
        "heading_1": 16,
        "heading_2": 16,
        "heading_3": 16,
        "body": 16
    }
}
def set_font(run, chinese_font, western_font):
    """強制設(shè)置字體 (解決WPS中字體不生效的問題)"""
    run.font.name = western_font
    r = run._element.rPr
    if r is not None:
        # 移除舊的東亞字體設(shè)置
        rFonts = r.find(qn('w:eastAsia'))
        if rFonts is not None:
            r.remove(rFonts)
        # 添加新的東亞字體
        new_rFonts = r.makeelement(qn('w:eastAsia'), {})
        new_rFonts.set(qn('w:val'), chinese_font)
        r.append(new_rFonts)
def process_document(input_path, output_path):
    """核心處理邏輯"""
    # --- 步驟1: 處理文件格式 ---
    file_ext = os.path.splitext(input_path)[1].lower()
    temp_docx_path = None
    if file_ext == ".doc":
        print("轉(zhuǎn)換中: .doc -> .docx")
        success, result = convert_doc_to_docx(input_path)
        if not success:
            return False, result
        temp_docx_path = result
        process_path = temp_docx_path
    elif file_ext == ".docx":
        process_path = input_path
    else:
        return False, "不支持的文件格式"
    try:
        doc = Document(process_path)
        # 設(shè)置頁邊距
        for section in doc.sections:
            section.top_margin = Cm(CONFIG["margin"][0])
            section.bottom_margin = Cm(CONFIG["margin"][1])
            section.left_margin = Cm(CONFIG["margin"][2])
            section.right_margin = Cm(CONFIG["margin"][3])
        # --- 步驟2: 遍歷段落并應(yīng)用自定義樣式 ---
        for para in doc.paragraphs:
            if not para.text.strip():
                continue
            text = para.text.strip()
            # 標(biāo)題1: 匹配 "一、" 格式
            if re.match(r'^[一二三四五六七八九十]、', text):
                pf = para.paragraph_format
                pf.first_line_indent = Pt(0) # 取消縮進(jìn)
                pf.alignment = WD_ALIGN_PARAGRAPH.LEFT
                pf.line_spacing_rule = CONFIG["line_rule"]
                pf.line_spacing = CONFIG["line_height"]
                for run in para.runs:
                    set_font(run, CONFIG["fonts"]["heading_1"], CONFIG["western_font"])
                    run.font.size = Pt(CONFIG["font_sizes"]["heading_1"])
                    run.font.bold = False
            # 標(biāo)題2: 匹配 "(一)" 格式
            elif re.match(r'^[((][\u4e00-\u9fa5]+[))]', text):
                pf = para.paragraph_format
                pf.first_line_indent = Pt(0)
                pf.alignment = WD_ALIGN_PARAGRAPH.LEFT
                pf.line_spacing_rule = CONFIG["line_rule"]
                pf.line_spacing = CONFIG["line_height"]
                for run in para.runs:
                    set_font(run, CONFIG["fonts"]["heading_2"], CONFIG["western_font"])
                    run.font.size = Pt(CONFIG["font_sizes"]["heading_2"])
                    run.font.bold = False
            # 標(biāo)題3: 匹配 "1." 或 "1、" 格式
            elif re.match(r'^\d+[\.、]', text):
                pf = para.paragraph_format
                pf.first_line_indent = Pt(0)
                pf.alignment = WD_ALIGN_PARAGRAPH.LEFT
                pf.line_spacing_rule = CONFIG["line_rule"]
                pf.line_spacing = CONFIG["line_height"]
                for run in para.runs:
                    set_font(run, CONFIG["fonts"]["heading_3"], CONFIG["western_font"])
                    run.font.size = Pt(CONFIG["font_sizes"]["heading_3"])
                    run.font.bold = True
            # 正文: 默認(rèn)樣式
            else:
                pf = para.paragraph_format
                pf.first_line_indent = Cm(0.74) # 首行縮進(jìn)2字符
                pf.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                pf.line_spacing_rule = CONFIG["line_rule"]
                pf.line_spacing = CONFIG["line_height"]
                for run in para.runs:
                    set_font(run, CONFIG["fonts"]["body"], CONFIG["western_font"])
                    run.font.size = Pt(CONFIG["font_sizes"]["body"])
                    run.font.bold = False
        # --- 步驟3: 處理文檔大標(biāo)題 (第1段) ---
        if len(doc.paragraphs) > 0:
            first_para = doc.paragraphs[0]
            if first_para.text.strip():
                pf = first_para.paragraph_format
                pf.alignment = WD_ALIGN_PARAGRAPH.CENTER
                pf.space_after = Pt(12)
                for run in first_para.runs:
                    set_font(run, CONFIG["fonts"]["title"], CONFIG["western_font"])
                    run.font.size = Pt(CONFIG["font_sizes"]["title"])
                    run.font.bold = False
        doc.save(output_path)
        # 清理臨時文件
        if temp_docx_path and os.path.exists(temp_docx_path):
            os.remove(temp_docx_path)
        return True, f"成功! 保存至: {output_path}"
    except Exception as e:
        if temp_docx_path and os.path.exists(temp_docx_path):
            os.remove(temp_docx_path)
        return False, f"處理異常: {str(e)}"
# --- 3. 美觀的GUI界面 (含自定義配置) ---
class ModernTypesettingApp:
    def __init__(self, root):
        self.root = root
        self.root.title("??? WPS 智能排版大師 (含自定義)")
        self.root.geometry("750x600")
        self.root.resizable(True, True)
        self.setup_styles()
        self.create_widgets()
    def setup_styles(self):
        style = ttk.Style()
        style.configure("TLabel", font=("微軟雅黑", 10))
        style.configure("TButton", font=("微軟雅黑", 9))
        self.root.configure(bg='#f5f5f5')
    def create_widgets(self):
        notebook = ttk.Notebook(self.root)
        notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        # --- Tab 1: 主操作界面 ---
        tab_main = ttk.Frame(notebook)
        notebook.add(tab_main, text="?? 文檔處理")
        main_frame = ttk.LabelFrame(tab_main, text=" 任務(wù)配置 ", padding=20)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        # 輸入輸出
        tk.Label(main_frame, text="輸入文件:", font=("微軟雅黑", 10)).grid(row=0, column=0, sticky=tk.W, pady=10)
        self.input_entry = tk.Entry(main_frame, width=40, font=("Consolas", 10), relief="solid")
        self.input_entry.grid(row=0, column=1, padx=10, pady=10, sticky=tk.EW)
        tk.Button(main_frame, text="?? 選擇文件", command=self.browse_input, bg="#007ACC", fg="white").grid(row=0, column=2, padx=10)
        tk.Label(main_frame, text="輸出目錄:", font=("微軟雅黑", 10)).grid(row=1, column=0, sticky=tk.W, pady=10)
        self.output_entry = tk.Entry(main_frame, width=40, font=("Consolas", 10), relief="solid")
        self.output_entry.grid(row=1, column=1, padx=10, pady=10, sticky=tk.EW)
        tk.Button(main_frame, text="?? 選擇文件夾", command=self.browse_output, bg="#28A745", fg="white").grid(row=1, column=2, padx=10)
        # 控制按鈕
        btn_frame = tk.Frame(main_frame)
        btn_frame.grid(row=2, column=0, columnspan=3, pady=30)
        self.start_btn = tk.Button(btn_frame, text="?? 開始排版", 
                                  command=self.start_process, 
                                  bg="#DC3545", fg="white", width=15, height=2, font=("微軟雅黑", 10, "bold"))
        self.start_btn.pack(side=tk.LEFT, padx=20)
        tk.Button(btn_frame, text="? 退出", command=self.root.quit, 
                 width=15, height=2).pack(side=tk.LEFT, padx=20)
        # 狀態(tài)欄
        self.status_var = tk.StringVar()
        self.status_var.set("就緒: 支持 .doc 和 .docx 格式")
        status_bar = tk.Label(self.root, textvariable=self.status_var, relief="sunken", 
                             bg="#e9ecef", fg="gray", font=("Consolas", 9))
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        # --- Tab 2: 字體配置界面 ---
        tab_config = ttk.Frame(notebook)
        notebook.add(tab_config, text="?? 字體配置")
        config_frame = ttk.LabelFrame(tab_config, text=" 自定義樣式設(shè)置 ", padding=20)
        config_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        # 字體選擇行
        tk.Label(config_frame, text="字體名稱", font=("微軟雅黑", 10, "bold")).grid(row=0, column=1, padx=40)
        tk.Label(config_frame, text="字號(磅)", font=("微軟雅黑", 10, "bold")).grid(row=0, column=2, padx=20)
        # 標(biāo)題配置
        tk.Label(config_frame, text="文檔大標(biāo)題:", fg="blue").grid(row=1, column=0, sticky=tk.W, pady=10)
        self.title_font = ttk.Combobox(config_frame, values=[
            '方正小標(biāo)宋_GBK', '黑體', '宋體', '微軟雅黑'
        ], width=15)
        self.title_font.set(CONFIG["fonts"]["title"])
        self.title_font.grid(row=1, column=1)
        self.title_size = ttk.Combobox(config_frame, values=[16, 18, 20, 22, 24, 26, 28], width=8)
        self.title_size.set(CONFIG["font_sizes"]["title"])
        self.title_size.grid(row=1, column=2)
        # 一級標(biāo)題
        tk.Label(config_frame, text="一級標(biāo)題(一、):", fg="darkgreen").grid(row=2, column=0, sticky=tk.W, pady=10)
        self.l1_font = ttk.Combobox(config_frame, values=[
            '黑體', '方正小標(biāo)宋_GBK', '楷體_GB2312'
        ], width=15)
        self.l1_font.set(CONFIG["fonts"]["heading_1"])
        self.l1_font.grid(row=2, column=1)
        self.l1_size = ttk.Combobox(config_frame, values=[14, 15, 16, 17, 18], width=8)
        self.l1_size.set(CONFIG["font_sizes"]["heading_1"])
        self.l1_size.grid(row=2, column=2)
        # 二級標(biāo)題
        tk.Label(config_frame, text="二級標(biāo)題((一)):", fg="purple").grid(row=3, column=0, sticky=tk.W, pady=10)
        self.l2_font = ttk.Combobox(config_frame, values=[
            '楷體_GB2312', '仿宋_GB2312', '黑體'
        ], width=15)
        self.l2_font.set(CONFIG["fonts"]["heading_2"])
        self.l2_font.grid(row=3, column=1)
        self.l2_size = ttk.Combobox(config_frame, values=[14, 15, 16, 17, 18], width=8)
        self.l2_size.set(CONFIG["font_sizes"]["heading_2"])
        self.l2_size.grid(row=3, column=2)
        # 正文配置
        tk.Label(config_frame, text="正文/三級標(biāo)題:", fg="gray").grid(row=4, column=0, sticky=tk.W, pady=10)
        self.body_font = ttk.Combobox(config_frame, values=[
            '仿宋_GB2312', '宋體', '黑體'
        ], width=15)
        self.body_font.set(CONFIG["fonts"]["body"])
        self.body_font.grid(row=4, column=1)
        self.body_size = ttk.Combobox(config_frame, values=[14, 15, 16, 17, 18], width=8)
        self.body_size.set(CONFIG["font_sizes"]["body"])
        self.body_size.grid(row=4, column=2)
        # 操作按鈕
        opt_frame = tk.Frame(config_frame)
        opt_frame.grid(row=5, column=0, columnspan=3, pady=30)
        tk.Button(opt_frame, text="?? 保存配置", command=self.save_config, 
                 bg="#17A2B8", fg="white", width=15).pack(side=tk.LEFT, padx=20)
        tk.Button(opt_frame, text="?? 恢復(fù)默認(rèn)", command=self.reset_config, 
                 bg="#6C757D", fg="white", width=15).pack(side=tk.LEFT, padx=20)
    def browse_input(self):
        file_path = filedialog.askopenfilename(
            title="選擇Word文檔",
            filetypes=[("Word文檔", "*.docx *.doc"), ("All Files", "*.*")]
        )
        if file_path:
            self.input_entry.delete(0, tk.END)
            self.input_entry.insert(0, file_path)
    def browse_output(self):
        dir_path = filedialog.askdirectory()
        if dir_path:
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, dir_path)
    def save_config(self):
        """保存用戶自定義的字體設(shè)置"""
        try:
            CONFIG["fonts"]["title"] = self.title_font.get()
            CONFIG["fonts"]["heading_1"] = self.l1_font.get()
            CONFIG["fonts"]["heading_2"] = self.l2_font.get()
            CONFIG["fonts"]["body"] = self.body_font.get()
            CONFIG["font_sizes"]["title"] = int(self.title_size.get())
            CONFIG["font_sizes"]["heading_1"] = int(self.l1_size.get())
            CONFIG["font_sizes"]["heading_2"] = int(self.l2_size.get())
            CONFIG["font_sizes"]["body"] = int(self.body_size.get())
            self.status_var.set("? 配置已更新,下次處理生效")
            messagebox.showinfo("成功", "字體配置已保存!")
        except Exception as e:
            messagebox.showerror("錯誤", f"配置保存失敗: {e}")
    def reset_config(self):
        """恢復(fù)默認(rèn)配置"""
        # 這里直接寫死默認(rèn)值
        self.title_font.set('方正小標(biāo)宋_GBK')
        self.l1_font.set('黑體')
        self.l2_font.set('楷體_GB2312')
        self.body_font.set('仿宋_GB2312')
        self.title_size.set(22)
        self.l1_size.set(16)
        self.l2_size.set(16)
        self.body_size.set(16)
        self.save_config()
        self.status_var.set("?? 已恢復(fù)默認(rèn)設(shè)置")
    def start_process(self):
        input_file = self.input_entry.get()
        output_dir = self.output_entry.get()
        if not input_file or not output_dir:
            messagebox.showwarning("警告", "請輸入文件路徑和輸出目錄!")
            return
        if not os.path.exists(input_file):
            messagebox.showerror("錯誤", "輸入文件不存在!")
            return
        # 生成輸出路徑
        filename = os.path.basename(input_file)
        name, ext = os.path.splitext(filename)
        output_file = os.path.join(output_dir, f"{name}_已排版{ext}")
        self.status_var.set("?? 正在處理中 (可能需要幾秒)...")
        self.root.update_idletasks()
        success, msg = process_document(input_file, output_file)
        if success:
            self.status_var.set("? 處理完成!")
            messagebox.showinfo("成功", f"任務(wù)完成!\n\n{msg}")
        else:
            self.status_var.set("? 處理失敗")
            messagebox.showerror("錯誤", f"處理失敗:\n{msg}")
if __name__ == "__main__":
    root = tk.Tk()
    app = ModernTypesettingApp(root)
    root.mainloop()

使用前準(zhǔn)備

1.安裝依賴:如果你有 .doc 文件需要處理,請務(wù)必在終端運行:

pip install pywin32

(如果沒有 .doc 文件,只處理 .docx,則不需要安裝)

2.字體庫:代碼中使用了 仿宋_GB2312 和 楷體_GB2312。如果你的電腦(特別是非Windows系統(tǒng))沒有這些字體,WPS 可能會顯示異常。如果報錯,可以在配置界面手動選擇系統(tǒng)中已有的字體(如“仿宋”、“楷體”)。

功能說明

  • Tab 1 (文檔處理):選擇你的 .doc 或 .docx 文件,點擊開始。
  • Tab 2 (字體配置):你可以在這里修改“文檔大標(biāo)題”、“一級標(biāo)題”、“二級標(biāo)題”和“正文”的字體及大小。修改后點擊“保存配置”,下次處理文檔時就會生效。

以上就是基于Python自動化實現(xiàn)Word文檔專業(yè)排版的詳細(xì)內(nèi)容,更多關(guān)于Python Word文檔排版的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

保靖县| 青冈县| 开鲁县| 台东市| 都匀市| 田阳县| 武平县| 枣庄市| 德安县| 临沧市| 彭州市| 密山市| 谷城县| 兴城市| 日土县| 高淳县| 枣阳市| 惠东县| 新安县| 定远县| 泾源县| 钦州市| 沙湾县| 福清市| 鄢陵县| 化德县| 长葛市| 安多县| 阆中市| 云阳县| 和林格尔县| 始兴县| 岳池县| 黄梅县| 崇信县| 土默特左旗| 宁南县| 临湘市| 繁峙县| 沙田区| 潮安县|