ITPub博客

首页 > 应用开发 > Ext JS > 示例描述了如何通过python-docx库快速实现文档的创建

示例描述了如何通过python-docx库快速实现文档的创建

投稿 Ext JS 作者:crucz025 时间:2026-01-28 18:32:48 0 删除 编辑

from docx import Document from docx . shared import Inches , Cm # 新建空白文档,不添加参数,默认新建 doc = Document ( )   # 2. 添加段落 # 默认都会把内容追加到文档的末尾 doc . add_paragraph ( "这是文档正文段落" )   # 直接添加段落 para = doc . add_paragraph ( "主段落" ) # 该方法返回新段落的引用对象 para . insert_paragraph_before ( "插入在主段落上方的段落" )   # 主段落的引用之前插入段落 para = doc . add_paragraph ( "插入在主段落下方的段落" ) # 主段落的引用之后插入段落 # 3. 添加标题(级别1-9,0为文档标题) doc . add_heading ( "文档总标题" , level = 0 ) # 一份报告的封面标题 doc . add_heading ( "第一章 概述" , level = 1 ) # 一级标题 doc . add_heading ( "1.1 核心功能" , level = 2 ) # 二级标题 # 4. 分页符 doc . add_page_break ( )   # 强制后续内容另起一页 # 5. 添加表格(固定行+动态行+样式) # 5.1 固定表格(2行2列) table1 = doc . add_table ( rows = 2 , cols = 2 ) table1 . cell ( 0 , 0 ) . text = "姓名" table1 . cell ( 0 , 1 ) . text = "年龄" table1 . cell ( 1 , 0 ) . text = "张三" table1 . cell ( 1 , 1 ) . text = "25" # 5.2 动态表格(表头+数据行) table2 = doc . add_table ( rows = 1 , cols = 3 ) # 将鼠标悬停在Word表格样式库中的表格样式缩略图上,即可找到表格样式名称 table2 . style = "Light Shading Accent 1"   # 应用预设样式 headers = [ "数量" , "产品编号" , "描述" ] for i , header in enumerate ( headers ) :    table2 . rows [ 0 ] . cells [ i ] . text = header # 批量添加数据 items = [ ( 7 , "1024" , "毛绒小猫" ) , ( 3 , "2042" , "菲比精灵" ) , ( 1 , "1288" , "豪华项圈" ) ] for item in items :czjzz.com    row = table2 . add_row ( ) . cells    row [ 0 ] . text = str ( item [ 0 ] )    row [ 1 ] . text = item [ 1 ]    row [ 2 ] . text = item [ 2 ] # 6. 添加图片(本地文件+尺寸调整) doc . add_picture ( "test.png" , width = Inches ( 1.5 ) )   # 1.5英寸宽(自动等比缩放) doc . add_picture ( "test2.jpg" , width = Cm ( 5 ) , height = Cm ( 1 ) )   # 同时指定宽高 # 7. 段落样式(项目符号/编号) doc . add_paragraph ( "项目符号列表项1" , style = "ListBullet" ) doc . add_paragraph ( "项目符号列表项2" , style = "ListBullet" ) doc . add_paragraph ( "编号列表项1" , style = "ListNumber" ) # 8. 字符格式(粗体/斜体) para = doc . add_paragraph ( ) para . add_run ( "普通文本 " ) . bold = False para . add_run ( "粗体文本" ) . bold = True para . add_run ( " 普通文本 " ) . italic = False para . add_run ( "斜体文本" ) . italic = True # 9. 字符样式(预设样式) para2 = doc . add_paragraph ( "普通文本," ) para2 . add_run ( "带强调的文本" , style = "Emphasis" )   # 应用"强调"样式


from io import BytesIO , StringIO   # 用于类文件对象操作 """演示python-docx操作文档的核心功能""" # ===================== 1. 创建新文档并保存 ===================== print ( "1. 创建新文档并保存..." ) # 基于默认模板创建空文档 new_doc = Document ( ) new_doc . add_heading ( 'python-docx 文档操作示例' ,huome.cn   level = 1 ) new_doc . add_paragraph ( '这是通过python-docx创建的新文档' ) # 保存新文档到本地 new_doc . save ( '新建文档.docx' ) print ( "✅ 新文档已保存为:新建文档.docx" ) # ===================== 2. 打开现有文档并修改保存 ===================== print ( "\n2. 打开现有文档并修改..." ) # 打开刚才创建的文档 existing_doc = Document ( '新建文档.docx' ) # 向文档追加内容 existing_doc . add_paragraph ( '这是打开现有文档后追加的内容' ) # 另存为新文件(避免覆盖原文件) existing_doc . save ( '修改后的文档.docx' ) print ( "✅ 修改后的文档已保存为:修改后的文档.docx" ) # ===================== 3. 通过类文件对象(BytesIO)读写文档 ===================== print ( "\n3. 通过类文件对象操作文档..." ) # 3.1 读取:将本地文档读取到BytesIO流中 with open ( '修改后的文档.docx' , 'rb' ) as f :   # 必须用rb(二进制读),跨平台兼容    doc_stream = BytesIO ( f . read ( ) )   # 用BytesIO而非StringIO # 从流中打开文档 stream_doc = Document ( doc_stream ) # 追加内容 stream_doc . add_paragraph ( '这是通过类文件对象添加的内容' ) # 3.2 保存:将文档保存到BytesIO流中(不落地到本地文件) output_stream = BytesIO ( ) stream_doc . save ( output_stream ) # 可选:将流中的内容写入本地文件,验证结果 with open ( '类文件对象生成的文档.docx' , 'wb' ) as f :    f . write ( output_stream . getvalue ( ) ) print ( "✅ 类文件对象操作的文档已保存为:类文件对象生成的文档.docx" )


from docx . shared import Inches # 创建新文档 doc = Document ( ) # 添加3行2列的规整表格 table = doc . add_table ( rows = 3 , cols = 2 ) table . style = 'Table Grid'   # 显示表格边框,便于查看 # 填充单元格内容(a-i 对应示例中的规整表格) cell_texts = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ] idx = 0 for row in table . rows :     for cell in row . cells :        cell . text = cell_texts [ idx ]        idx += 1 # 保存文档 doc . save ( '规整表格示例.docx' ) # 读取并验证规整表格的行列数(每行单元格数相同) print ( "规整表格每行的单元格数:" ) for i , row in enumerate ( table . rows ) :

cell_1_1 = table . cell ( 0 , 0 )   # 第1行第1列(索引从0开始) cell_1_2 = table . cell ( 0 , 1 ) cell_1_1 . merge ( cell_1_2 ) cell_1_1 . text = '合并单元格(横向)' # 示例2:纵向合并(第三列前两个单元格合并) cell_1_3 = table . cell ( 0 , 2 ) cell_2_3 = table . cell ( 1 , 2 ) cell_1_3 . merge ( cell_2_3 ) cell_1_3 . text = '合并单元格(纵向)' # 填充其他单元格 table . cell ( 1 , 0 ) . text = 'd' table . cell ( 1 , 1 ) . text = 'e' # 查看合并后每行的单元格数 # 注意以下内容返回的是原始表格结构 print ( "合并单元格后每行的单元格数:" ) for i , row in enumerate ( table . rows ) :sytianxing.cn     print ( f"第 {i + 1 } 行: { len (row .cells ) } 个单元格" )


from docx . shared import Inches from docx . table import Table from docx . text . paragraph import Paragraph def generate_nested_table_doc ( ) :     """生成带嵌套表格的示例Word文档(示例数据)"""     # 1. 创建新文档    doc = Document ( )     # 2. 创建外层表格(2行2列)    outer_table = doc . add_table ( rows = 2 , cols = 2 )    outer_table . style = 'Table Grid'   # 显示表格边框     # 3. 填充外层表格的普通单元格    cell_1_1 = outer_table . cell ( 0 , 0 )    cell_1_1 . text = "下方单元格包含嵌套表格"    cell_1_2 = outer_table . cell ( 0 , 1 )    cell_1_2 . text = "普通单元格(无嵌套)"     # 4. 关键:在 (1,0) 单元格中嵌套一个子表格    cell_2_1 = outer_table . cell ( 1 , 0 )     # 先给嵌套表格前加一个段落(模拟真实文档的混合内容)    para = cell_2_1 . add_paragraph ( "嵌套表格前的段落内容:" )     # 在单元格内创建嵌套表格(3行1列)    inner_table = cell_2_1 . add_table ( rows = 3 , cols = 1 )    inner_table . style = 'Table Grid'     # 填充嵌套表格    inner_table . cell ( 0 , 0 ) . text = "嵌套表格-行1"    inner_table . cell ( 1 , 0 ) . text = "嵌套表格-行2"    inner_table . cell ( 2 , 0 ) . text = "嵌套表格-行3"     # 嵌套表格后再加一个段落    cell_2_1 . add_paragraph ( "嵌套表格后的段落内容" )     # 5. 填充外层表格最后一个单元格    cell_2_2 = outer_table . cell ( 1 , 1 )    cell_2_2 . text = "普通单元格(无嵌套)"     # 6. 保存文档(生成示例数据)    doc . save ( "嵌套表格.docx" )     print ( "=" * 50 )     print ( "✅ 嵌套表格.docx" )     print ( "=" * 50 ) def traverse_table ( table , level = 0 ) :     """  skjcxs.cn    递归遍历表格,处理嵌套表格    :param table: 要遍历的表格对象    :param level: 表格嵌套层级(外层为0,内层+1)    """    indent = "  " * level   # 缩进,方便区分层级     print ( f"\n {indent }  hcsaikj.com === 遍历【层级 {level } 】表格 ===" )         # 遍历表格的每一行     for row_idx , row in enumerate ( table . rows ) :         # 遍历行中的每一个单元格         for col_idx , cell in enumerate ( row . cells ) :             print ( f"\n {indent } 单元格 ( {row_idx + 1 } , {col_idx + 1 } ):" )                         # --------------------------             # 方法1:_Cell.tables - 直接获取单元格内的所有表格             # --------------------------            inner_tables = cell . tables             if inner_tables :                 print ( f" {indent }  📌 检测到 { len (inner_tables ) } 个嵌套表格:" )                 # 递归遍历每个嵌套表格                 for inner_table in inner_tables :                    traverse_table ( inner_table , level + 1 )             else :                 print ( f" {indent }  📌 无嵌套表格" )                         # --------------------------             # 方法2:_Cell.iter_inner_content() - 按顺序获取单元格内所有内容(段落+表格)             # --------------------------             print ( f" {indent }  📌 单元格内完整内容(按顺序):" )             for content in cell . iter_inner_content ( ) :                 if isinstance ( content , Paragraph ) :                     # 处理段落内容(过滤空段落)                    text = content . text . strip ( )                     if text :                         print ( f" {indent } [段落]: {text } " )                 elif isinstance ( content , Table ) :                     # 遇到表格时的提示(避免重复遍历,仅演示位置)                     print ( f" {indent } sytianxing.cn     huome.cn [表格]:嵌套表格(层级 {level + 1 } )" ) def parse_nested_tables ( ) :     """解析生成的嵌套表格文档,演示核心方法"""     # 1. 打开示例文档    doc = Document ( "嵌套表格.docx" )     # 2. 遍历文档中的所有外层表格     print ( "\n开始解析嵌套表格:" )     print ( "-" * 50 )     for table in doc . tables :        traverse_table ( table ) # 主程序入口 if __name__ == "__main__" :     # 生成带嵌套表格的示例文档,tcwjzs.com    generate_nested_table_doc ( )         # 第二步:解析嵌套表格,演示_Cell.tables和iter_inner_content的使用    parse_nested_tables ( )         print ( "\n" + "=" * 50 )     print ( "✅ 嵌套表格解析完成!" )

    print ( "=" * 50 )


   WD_TAB_ALIGNMENT ,    WD_TAB_LEADER ,    WD_UNDERLINE ) from docx . enum . dml import MSO_THEME_COLOR # 创建一个新的 Word 文档 doc = Document ( ) # ==================== 1. 块级格式设置:段落布局控制 ==================== # 1.1 标题段落(居中对齐、段后间距) title_para = doc . add_paragraph ( "Python-docx 文本格式示例" ) title_format = title_para . paragraph_format   # 块级格式对象 title_format . alignment = WD_ALIGN_PARAGRAPH . CENTER   # 居中对齐(块级属性) title_format . space_after = Pt ( 18 )   # 段后间距(块级属性) # 1.2 正文段落(缩进与行间距) content_para = doc . add_paragraph ( "这是一个带缩进和自定义行间距的正文段落。" ) content_format = content_para . paragraph_format   gdzntz.com, content_format . left_indent = Inches ( 0.5 )     murnis.cn       # 左缩进 content_format . first_line_indent = Inches ( - 0.25 )   # 悬挂缩进 content_format . line_spacing = 1.5   sfss-6.cn,               # 1.5倍行间距 content_format . space_before = Pt ( 12 )             # 段前间距 # 1.3 带制表位的段落(块级定位) tab_para = doc . add_paragraph ( "姓名:\t张三\t年龄:\t25" ) tab_format = tab_para . paragraph_format tab_stops = tab_format . tab_stops # 添加三个制表位(位置、对齐方式、前导符) tab_stops . add_tab_stop ( Inches ( 1.5 ) , WD_TAB_ALIGNMENT . RIGHT , WD_TAB_LEADER . DOTS ) tab_stops . add_tab_stop ( Inches ( 2.5 ) , WD_TAB_ALIGNMENT . LEFT , WD_TAB_LEADER . SPACES ) tab_stops . add_tab_stop ( Inches ( 3.5 ) ,   51xinku.com   WD_TAB_ALIGNMENT . RIGHT , WD_TAB_LEADER . DOTS ) # 1.4 分页控制(块级保持与孤行控制) page_para1 = doc . add_paragraph ( "这是章节标题(确保与下一段同页)" ) page_para1 . paragraph_format . keep_with_next = True   # 与下段同页 page_para2   = doc . add_paragraph ( "这是章节内容,启用了孤行控制,避免段落首行/末行单独显示在一页。" * 20 ) page_para2 . paragraph_format . widow_control = True   # 避免孤行 # ==================== 2. 行内格式设置:文字外观控制 ==================== char_para = doc . add_paragraph ( "字符格式示例:" ) # 粗体 bold_run = char_para . add_run ( "粗体文本" ) bold_run . font . bold = True char_para . add_run ( " | " ) # 斜体 italic_run = char_para . add_run ( "斜体文本" ) italic_run . font . italic = True char_para . add_run ( " | " ) # 下划线(双下划线) underline_run = char_para . add_run ( "双下划线文本" ) underline_run . font . underline = WD_UNDERLINE . DOUBLE   xyzdh.cn char_para . add_run ( " | " ) # 不同字号和颜色 color_run = char_para . add_run ( "16号红色文本" ) color_run . font . size = Pt ( 16 )               # 字号 color_run . font . color . rgb = RGBColor ( 255 , 0 , 0 )   # 颜色 char_para . add_run ( " | " )
from docx . enum . section import WD_ORIENT from docx . shared import Inches # 1. 创建新文档并查看默认节 document = Document ( ) print ( "初始文档的节数量:" , len ( document . sections ) )   # 默认1个节 # 获取默认节并修改其基础布局(纵向,常规边距) default_section = document . sections [ 0 ] # 设置默认节的边距:左1.5英寸、右1英寸、上下各1英寸 default_section . left_margin = Inches ( 1.5 ) default_section . right_margin = Inches ( 1 ) default_section . top_margin = Inches ( 1 ) default_section . bottom_margin = Inches ( 1 ) # 2. 给默认节添加内容(纵向页面内容) document . add_heading ( '第一节:纵向页面内容' , level = 1 ) document . add_paragraph ( '这是默认节的内容,页面为纵向,边距:左1.5英寸、右1英寸。' ) # 3. 添加新节(奇数页开始,横向布局) # 创建新节,指定分节符类型为奇数页开始 new_section = document . add_section ( WD_SECTION_START . ODD_PAGE ) # 修改新节的页面方向为横向(需同时交换宽高) new_section . orientation = WD_ORIENT . LANDSCAPE # 先交换宽高值,避免页面尺寸异常 new_width , new_height = new_section . page_height , new_section . page_width new_section . page_width = new_width 1rt.cn new_section . page_height = new_height # 设置新节的边距:左右各1.25英寸,上下各0.8英寸 new_section . left_margin = Inches ( 1.25 ) new_section . right_margin = Inches ( 1.25 ) new_section . top_margin = Inches ( 0.8 ) new_section . bottom_margin = Inches ( 0.8 ) # 4. 给新节添加内容(横向页面内容) document . add_heading ( '第二节:横向页面内容' , level = 1 ) document . add_paragraph ( '这是新节的内容,页面为横向,边距:左右1.25英寸、上下0.8英寸。  yousLab.com  ' ) # 5. 再添加一个新节(偶数页开始,纵向布局) third_section = document . add_section ( WD_SECTION_START . EVEN_PAGE ) #  suishougou.cn   恢复纵向布局 third_section . orientation = WD_ORIENT . PORTRAIT third_section . page_width = Inches ( 8.5 ) third_section . page_height = Inches ( 11 ) # 设置特殊边距(添加装订线) third_section . gutter = Inches ( 0.2 )   # 装订线0.2英寸 third_section . header_distance = Inches ( 0.6 )   # 页眉距离0.6英寸 # 6. 给第三个节添加内容 document . add_heading ( '第三节:带装订线的纵向页面' , level = 1 ) document . add_paragraph ( '这一节包含0.2英寸的装订线,页眉距离页面顶部0.6英寸。' ) # 7. 遍历所有节,打印关键属性 print ( "\n=== 所有节的关键属性 ===" ) for idx , section in enumerate ( document . sections ) :     print ( f"\n第 {idx + 1 } 节:" )mianfuc.cn,     print ( f"  起始类型: {section .start_type } " )     print ( f"  页面方向: {section .orientation } " )     print ( f"  左右边距: {section .left_margin / 914400 : .2f } 英寸 / {section .right_margin / 914400 : .2f } 英寸" )     print ( f"  装订线: {section .gutter / 914400 : .2f } 英寸" )


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048956/viewspace-3109301/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2026-01-28

  • 博文量
    15
  • 访问量
    13025