往docx写入表格信息为什么没有写入进去呢

您可以解析一下那个表格信息 ,在按照我测试的代码写入就可以看见问题了

我的测试数据,就是从文档读取出来的合并规则,合并规则是没有问题的,问题在于写入到docx里面

就是用的这个代码进行写入 和读取的

@hhh1111 我执行了提供的代码,根据 docx 表数据创建了 json:

[
	{
		"type": "title",
		"level": 1,
		"contents": "1、你好"
	},
	{
		"type": "text",
		"contents": "哈哈哈哈哈"
	},
	{
		"type": "table",
		"content": [
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 2,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "机构"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "负责人"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 4,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "研究中心"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 2,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "广东省人民医院"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "主要研究者:吴一龙"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": ""
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": ""
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "主要研究者:杨衿记"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": ""
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "浙江大学附属第一医院"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "主要研究者:周建英"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": ""
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "湖南省肿瘤医院"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "主要研究者:杨农"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "申办方"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "江苏万邦生化医药集团有限责任公司"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "项目负责人:周永春"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "合同研究组织"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "北京复星医药科技开发有限公司"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "项目经理:程艳秋"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "生物检测单位"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "广东省人民医院I期研究室"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "项目负责人:王曦培"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "数据管理单位"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "北京复星医药科技开发有限公司"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "数据管理经理:蔡红霞"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "统计单位"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "北京复星医药科技开发有限公司"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "生物统计经理:周艳玲"
									}
								]
							}
						]
					}
				]
			},
			{
				"type": "tableRow",
				"content": [
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "中心实验室"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "昆皓睿诚医药研发(北京)有限公司"
									}
								]
							}
						]
					},
					{
						"type": "tableCell",
						"attrs": {
							"colspan": 1,
							"rowspan": 1,
							"colwidth": "None"
						},
						"content": [
							{
								"type": "paragraph",
								"content": [
									{
										"type": "text",
										"text": "项目经理:辜朝霞"
									}
								]
							}
						]
					}
				]
			}
		]
	},
	{
		"type": "title",
		"leve": 1,
		"contents": "哈哈哈哈"
	}
]

并更新了代码,得到了正确的结果:

# 创建一个新的文档
doc = aw.Document()
builder = aw.DocumentBuilder(doc)

# 遍历节(section)
for section in sections:
    if section["type"] == 'title':
        # 设置标题样式
        level = section.get('level', 1)
        builder.paragraph_format.style_identifier = getattr(
            aw.StyleIdentifier, f"HEADING{level}"
        )
        # 添加标题内容
        new_run = builder.font
        # 设置西文和中文字体
        new_run.size = 12
        new_run.name = "Times New Roman"  # 设置西文是新罗马字体
        new_run.name_far_east = "宋体"
        # 添加标题内容
        title = section.get('contents', '')  # 获取标题内容
        builder.writeln(title)  # 写入标题到文档

    elif section["type"] == 'text':
        # 添加文本内容
        new_run = builder.font
        # 设置西文和中文字体
        new_run.name = "Times New Roman"  # 设置西文是新罗马字体
        new_run.name_far_east = "宋体"
        new_run.size = 12
        text_content = section.get('contents', '')  # 获取文本内容
        builder.paragraph_format.character_unit_first_line_indent = 2
        builder.paragraph_format.line_spacing = 18
        builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
        builder.paragraph_format.line_unit_after = 0
        builder.paragraph_format.space_after = 0
        builder.writeln(text_content)  # 写入文本到文档

    elif section["type"] == 'table':
        # 添加表格内容
        table = builder.start_table()  # 开始一个新表格
        #  记录rowspan的数据
        table_data = section["contents"]
        for i in range(len(table_data)):
            cell_data_index = 0
            for row_data in table_data[i].get('content', []):
                # 遍历表格单元格
                for cell_data in row_data.get('content', []):
                    new_cell = builder.insert_cell()  # 插入新的表格行
                    builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE

                    row_index = table.index_of(new_cell)
                    cell_index = new_cell.parent_row.index_of(new_cell)

                    previous_row = table.rows[row_index - 1]
                    if previous_row is not None:
                        previous_cell = previous_row.cells[cell_index]
                        if previous_cell is not None and \
                                (previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.FIRST or
                                 previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.PREVIOUS):
                            for y in range(i, -1, -1):
                                curr_row_span = table_data[y].get('content', [])[cell_data_index].get('attrs',
                                                                                                      {}).get(
                                    'rowspan', 1)
                                if curr_row_span > 1:
                                    if curr_row_span >= table.rows.count - y:
                                        builder.cell_format.vertical_merge = aw.tables.CellMerge.PREVIOUS
                                    else:
                                        builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE

                    builder.cell_format.horizontal_merge = aw.tables.CellMerge.NONE
                    cell_content = ''  # 单元格内容初始化为空字符串
                    if isinstance(cell_data, dict):  # 检查单元格内容是否为字典类型
                        for paragraph_content in cell_data.get('content', []):
                            text = paragraph_content["text"]  # 获取段落文本内容
                            cell_content += text  # 将段落内容添加到单元格内容中
                    else:
                        cell_content = cell_data  # 如果不是字典类型,则直接使用内容

                    new_cell.cell_format.wrap_text = True  # 设置单元格内容自动换行
                    new_cell.cell_format.vertical_alignment = aw.tables.CellVerticalAlignment.CENTER  # 设置单元格内容垂直居中

                    builder.write(cell_content)  # 写入单元格内容

                    colspan = row_data.get('attrs', {}).get('colspan', 1)  # 获取列合并数
                    rowspan = row_data.get('attrs', {}).get('rowspan', 1)  # 获取行合并数

                    if colspan > 1 and rowspan > 1:
                        builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST
                        builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST  # 水平合并第一个单元格
                        for i in range(1, colspan):
                            builder.insert_cell()
                            builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
                    elif colspan > 1:
                        builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST  # 水平合并第一个单元格
                        for i in range(1, colspan):
                            builder.insert_cell()
                            builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
                    elif rowspan > 1:
                        builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST  # 垂直合并第一个单元格

                    cell_data_index += 1

            builder.end_row()
        builder.end_table()
# 保存文档
doc.save("output.docx")

下面是生成的文件:
output.docx (8.2 KB)

问题出在以下几行代码中,在这些代码中,rowspan 数据与当前表格行数进行了比较。已将其改为考虑第一条合并行,而第一条合并行并非总是从表的开头开始。

for y in range(i, -1, -1):
    curr_row_span = table_data[y].get('content', [])[cell_data_index].get('attrs', {}).get('rowspan', 1)
    if curr_row_span > 1:
        break

改为:

for y in range(i, -1, -1):
    curr_row_span = table_data[y].get('content', [])[cell_data_index].get('attrs',{}).get('rowspan', 1)
    if curr_row_span > 1:
        if curr_row_span >= table.rows.count - y:
            builder.cell_format.vertical_merge = aw.tables.CellMerge.PREVIOUS
        else:
            builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE

image.png (467.3 KB)

为什么写入的表格内容会有益出现象,需要怎么设置样式呢

@hhh1111 您可以使用 “table.auto_fit(aw.tables.AutoFitBehavior.AUTO_FIT_TO_WINDOW)”,或缩小表格内容的字体大小。

 builder.end_row()
        builder.end_table()
        table.auto_fit(aw.tables.AutoFitBehavior.AUTO_FIT_TO_WINDOW)

我设置的样式并没有生效,需要怎么实现呢

@hhh1111 请随表附上输入文件。

image.png (385.0 KB)

怎么在这两个表格之前插入一个换行呢,为什么下面的表格没有100%适应

@hhh1111 要添加换行符,可以使用 DocumentBuilder - builder.insert_break(aw.BreakType.LINE_BREAK)
看来您要合并的表有不同的列,所以才会出现这种情况。

你好怎么设置表格边框为虚线呢 下面这种样式
image.png (99.3 KB)

我进行样式设置写入的所有内容都有边框了

def refactor_template(sections, task_id):
    file_path = os.path.join(settings.DOWNLOAD_PATH, f"{task_id}.docx")
    doc = aw.Document()
    builder = aw.DocumentBuilder(doc)
    for section in sections:
        builder.paragraph_format.clear_formatting()
        if section["type"] == 'title':
            # 设置标题样式
            level = section.get('level', 1)
            builder.paragraph_format.style_identifier = getattr(
                aw.StyleIdentifier, f"HEADING{level}"
            )
            # 添加标题内容
            new_run = builder.font
            # 设置西文和中文字体
            new_run.size = 12
            new_run.name = "Times New Roman"  # 设置西文是新罗马字体
            new_run.name_far_east = "宋体"
            new_run.bold = True
            # 添加标题内容
            title = section.get('contents', '').strip()  # 获取标题内容
            builder.writeln(title)  # 写入标题到文档
        
        elif section["type"] == 'text':
            # 添加文本内容
            new_run = builder.font
            # 设置西文和中文字体
            new_run.name = "Times New Roman"  # 设置西文是新罗马字体
            new_run.bold = False
            new_run.name_far_east = "宋体"
            new_run.size = 12
            text_content = section.get('contents', '').strip()  # 获取文本内容
            builder.paragraph_format.character_unit_first_line_indent = 2
            builder.paragraph_format.line_spacing = 18
            builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
            builder.paragraph_format.line_unit_after = 0
            builder.paragraph_format.space_after = 0
            if text_content.startswith("表"):
                builder.paragraph_format.alignment = aw.ParagraphAlignment.CENTER
                new_run.bold = True
            builder.writeln(text_content)  # 写入文本到文档
        elif section["type"] == 'table':
            # 添加表格内容
            table = builder.start_table()  # 开始一个新表格
            new_run = builder.font
            new_run.bold = False
            new_run.size = 8
            #  记录rowspan的数据
            table_data = section["contents"]
            for i in range(len(table_data)):
                cell_data_index = 0
                for row_data in table_data[i].get('content', []):
                    # 遍历表格单元格
                    for cell_data in row_data.get('content', []):
                        new_cell = builder.insert_cell()  # 插入新的表格行
                        builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE

                        row_index = table.index_of(new_cell)
                        cell_index = new_cell.parent_row.index_of(new_cell)

                        previous_row = table.rows[row_index - 1]
                        if previous_row is not None:
                            previous_cell = previous_row.cells[cell_index]
                            if previous_cell is not None and \
                                    (previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.FIRST or
                                     previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.PREVIOUS):
                                for y in range(i, -1, -1):
                                    curr_row_span = table_data[y].get('content', [])[cell_data_index].get('attrs',
                                                                                                          {}).get(
                                        'rowspan', 1)
                                    if curr_row_span > 1:
                                        if curr_row_span >= table.rows.count - y:
                                            builder.cell_format.vertical_merge = aw.tables.CellMerge.PREVIOUS
                                        else:
                                            builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE

                        builder.cell_format.horizontal_merge = aw.tables.CellMerge.NONE
                        cell_content = ''  # 单元格内容初始化为空字符串
                        if isinstance(cell_data, dict):  # 检查单元格内容是否为字典类型
                            for paragraph_content in cell_data.get('content', []):
                                text = paragraph_content["text"]  # 获取段落文本内容
                                cell_content += text  # 将段落内容添加到单元格内容中

                        else:
                            cell_content = cell_data  # 如果不是字典类型,则直接使用内容

                        new_cell.cell_format.wrap_text = True  # 设置单元格内容自动换行
                        new_cell.cell_format.vertical_alignment = aw.tables.CellVerticalAlignment.CENTER  # 设置单元格内容垂直居中

                        builder.write(cell_content)  # 写入单元格内容

                        colspan = row_data.get('attrs', {}).get('colspan', 1)  # 获取列合并数
                        rowspan = row_data.get('attrs', {}).get('rowspan', 1)  # 获取行合并数

                        if colspan > 1 and rowspan > 1:
                            builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST
                            builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST  # 水平合并第一个单元格
                            for i in range(1, colspan):
                                builder.insert_cell()
                                builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
                        elif colspan > 1:
                            builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST  # 水平合并第一个单元格
                            for i in range(1, colspan):
                                builder.insert_cell()
                                builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
                        elif rowspan > 1:
                            builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST  # 垂直合并第一个单元格
                        cell_data_index += 1
                builder.end_row()
            builder.end_table()
            table.auto_fit(aw.tables.AutoFitBehavior.AUTO_FIT_TO_WINDOW)
    # 保存文档
    doc.save(file_path)
    return task_id

并且我设置的清除样式也没生效

@hhh1111 添加以下一行

new_cell.cell_format.borders.line_style = aw.LineStyle.DASH_SMALL_GAP

就像这样

for cell_data in row_data.get('content', []):
	new_cell = builder.insert_cell()  # 插入新的表格行
        new_cell.cell_format.borders.line_style = aw.LineStyle.DASH_SMALL_GAP
	builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE

还需要变更一下 第一行的下边框和最后一行的上边框设置成实线

def refactor_template(sections, task_id):
    file_path = os.path.join(settings.DOWNLOAD_PATH, f"{task_id}.docx")
    doc = aw.Document()
    builder = aw.DocumentBuilder(doc)
    for section in sections:
        builder.paragraph_format.clear_formatting()
        if section["type"] == 'title':
            # 设置标题样式
            level = section.get('level', 1)
            builder.paragraph_format.style_identifier = getattr(
                aw.StyleIdentifier, f"HEADING{level}"
            )
            # 添加标题内容
            new_run = builder.font
            # 设置西文和中文字体
            new_run.size = 12
            new_run.name = "Times New Roman"  # 设置西文是新罗马字体
            new_run.name_far_east = "宋体"
            new_run.bold = True
            # 添加标题内容
            title = section.get('contents', '').strip()  # 获取标题内容
            builder.writeln(title)  # 写入标题到文档

        elif section["type"] == 'text':
            # 添加文本内容
            new_run = builder.font
            # 设置西文和中文字体
            new_run.name = "Times New Roman"  # 设置西文是新罗马字体
            new_run.bold = False
            new_run.name_far_east = "宋体"
            new_run.size = 12
            text_content = section.get('contents', '').strip()  # 获取文本内容
            builder.paragraph_format.character_unit_first_line_indent = 2
            builder.paragraph_format.line_spacing = 18
            builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
            builder.paragraph_format.line_unit_after = 0
            builder.paragraph_format.space_after = 0
            if text_content.startswith("表"):
                builder.paragraph_format.alignment = aw.ParagraphAlignment.CENTER
                new_run.bold = True
            print(text_content)
            builder.writeln(text_content)  # 写入文本到文档
        elif section["type"] == 'image':
            # 插入图片
            image_path = section.get('contents', '').strip()
            builder.insert_image(image_path)
        elif section["type"] == 'table':
            # 添加表格内容
            table = builder.start_table()  # 开始一个新表格
            new_run = builder.font
            new_run.bold = False
            new_run.size = 8
            #  记录rowspan的数据
            table_data = section["contents"]
            for i in range(len(table_data)):
                cell_data_index = 0
                for row_data in table_data[i].get('content', []):
                    # 遍历表格单元格
                    for cell_data in row_data.get('content', []):
                        new_cell = builder.insert_cell()  # 插入新的表格行
                        new_cell.cell_format.borders.line_style = aw.LineStyle.DASH_LARGE_GAP
                        builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE

                        row_index = table.index_of(new_cell)
                        cell_index = new_cell.parent_row.index_of(new_cell)

                        previous_row = table.rows[row_index - 1]
                        if previous_row is not None:
                            previous_cell = previous_row.cells[cell_index]
                            if previous_cell is not None and \
                                    (previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.FIRST or
                                     previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.PREVIOUS):
                                for y in range(i, -1, -1):
                                    curr_row_span = table_data[y].get('content', [])[cell_data_index].get('attrs',
                                                                                                          {}).get(
                                        'rowspan', 1)
                                    if curr_row_span > 1:
                                        if curr_row_span >= table.rows.count - y:
                                            builder.cell_format.vertical_merge = aw.tables.CellMerge.PREVIOUS
                                        else:
                                            builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE

                        builder.cell_format.horizontal_merge = aw.tables.CellMerge.NONE
                        cell_content = ''  # 单元格内容初始化为空字符串
                        if isinstance(cell_data, dict):  # 检查单元格内容是否为字典类型
                            for paragraph_content in cell_data.get('content', []):
                                text = paragraph_content["text"]  # 获取段落文本内容
                                cell_content += text  # 将段落内容添加到单元格内容中

                        else:
                            cell_content = cell_data  # 如果不是字典类型,则直接使用内容

                        new_cell.cell_format.wrap_text = True  # 设置单元格内容自动换行
                        new_cell.cell_format.vertical_alignment = aw.tables.CellVerticalAlignment.CENTER  # 设置单元格内容垂直居中

                        builder.write(cell_content)  # 写入单元格内容

                        colspan = row_data.get('attrs', {}).get('colspan', 1)  # 获取列合并数
                        rowspan = row_data.get('attrs', {}).get('rowspan', 1)  # 获取行合并数

                        if colspan > 1 and rowspan > 1:
                            builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST
                            builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST  # 水平合并第一个单元格
                            for i in range(1, colspan):
                                builder.insert_cell()
                                builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
                        elif colspan > 1:
                            builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST  # 水平合并第一个单元格
                            for i in range(1, colspan):
                                builder.insert_cell()
                                builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
                        elif rowspan > 1:
                            builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST  # 垂直合并第一个单元格
                        cell_data_index += 1
                builder.end_row()

            builder.end_table()
            builder.insert_break(aw.BreakType.LINE_BREAK)
            table.auto_fit(aw.tables.AutoFitBehavior.AUTO_FIT_TO_WINDOW)
    # 保存文档
    doc.save(file_path)
    return task_id

还存在一个问题 怎么判断如果连续插入2个表格进行插入一个换行。目前插入的内容多了换行
image.png (119.5 KB)

只需要表格和表格直接插入换行

@hhh1111 在这种情况下,最简单的方法就是在创建表格后进行操作:

for row in table.rows:
    row = row.as_row()
    if row.is_first_row:
        for cell in row.cells:
            cell = cell.as_cell()
            cell.cell_format.borders.bottom.line_style = aw.LineStyle.SINGLE
        for cell in row.next_row.cells:
            cell = cell.as_cell()
            cell.cell_format.borders.top.line_style = aw.LineStyle.SINGLE

    if row.is_last_row:
        for cell in row.cells:
            cell = cell.as_cell()
            cell.cell_format.borders.top.line_style = aw.LineStyle.SINGLE
        for cell in row.previous_row.cells:
            cell = cell.as_cell()
            cell.cell_format.borders.bottom.line_style = aw.LineStyle.SINGLE

# 保存文档
doc.save("output.docx")

@hhh1111 我用表格创建了数据,使用您的代码后,换行没有问题,表格之间只有一个换行符。

原文件
image.jpg (157.7 KB)

写入文件的样式
image.png (417.8 KB)

请问为什么样式错乱了,还多了一些乱码的内容

image.png (67.0 KB)

每个段落结尾都多了一个换行 不想要这个换行。只需要在2个表格之前添加
image.png (137.1 KB)