Python实现Excel数据导出为Word双列表格的技术咨询
问题描述
我用Python写了一个程序,能从Excel提取信息导入Word文档,但现在生成的是垂直排列的单列表格(每行一个独立的2列小表格),需要改成双列布局(一行放两个小表格)。
现有代码:
import tkinter as tk from tkinter import filedialog import openpyxl from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.shared import Inches, Cm # Create the main window root = tk.Tk() root.withdraw() # Open a file dialog to select the Excel file file_path = filedialog.askopenfilename(title="Select Excel file", filetypes=(('Excel files', '*.xlsx'), ('All files', '*.*'))) # Open the Excel file and select the worksheet wb = openpyxl.load_workbook(file_path) sheet = wb['Sheet1'] doc = Document() # Create tables for i in range(2, sheet.max_row + 1): if sheet[f'B{i}'].value: for j in range(int(sheet[f'F{i}'].value)): table = doc.add_table(rows=6, cols=2) table.style = 'Table Grid' table.autofit = False # Modify the width of the first column for cell in table.columns[0].cells: cell.width = Cm(2.5) # Modify the width of the second column for cell in table.columns[1].cells: cell.width = Cm(5.5) # Add a blank paragraph between each table doc.add_paragraph("\n") nos = sheet[f"B{i}"].value if sheet[f"B{i}"].value else "N/A" nom_nr = sheet[f"J{i}"].value if sheet[f"J{i}"].value else "N/A" kods = sheet[f"D{i}"].value if sheet[f"D{i}"].value else "N/A" pas_nr = sheet[f"K{i}"].value if sheet[f"K{i}"].value else "N/A" table.cell(0, 0).text = "Nos." table.cell(0, 1).text = str(nos) table.cell(1, 0).text = "Nom. Nr." table.cell(1, 1).text = str(nom_nr) table.cell(2, 0).text = "Kods" table.cell(2, 1).text = str(kods) table.cell(3, 0).text = "Pas. Nr." table.cell(3, 1).text = str(pas_nr) table.cell(4, 0).text = "Daudzums" table.cell(4, 1).text = "1000" table.cell(5, 0).text = "Izpildītājs" table.cell(5, 1).text = "SIA “STS Group”\nCeļāres 2B, Spilve, Babītes pag.\nTel. 29211780" # Save the Word document doc.save('data.docx')
修改方案
核心思路
先收集所有需要生成的小表格数据,再按每2个一组的方式,用一个大表格作为容器承载每组的两个小表格,实现双列并排效果。
修改后代码
import tkinter as tk from tkinter import filedialog import openpyxl from docx import Document from docx.shared import Cm from docx.enum.table import WD_TABLE_ALIGNMENT # Create the main window root = tk.Tk() root.withdraw() # Open a file dialog to select the Excel file file_path = filedialog.askopenfilename(title="Select Excel file", filetypes=(('Excel files', '*.xlsx'), ('All files', '*.*'))) # Open the Excel file and select the worksheet wb = openpyxl.load_workbook(file_path) sheet = wb['Sheet1'] doc = Document() # 第一步:收集所有需要生成的小表格数据 table_data_list = [] for i in range(2, sheet.max_row + 1): if sheet[f'B{i}'].value: count = int(sheet[f'F{i}'].value) for _ in range(count): nos = sheet[f"B{i}"].value if sheet[f"B{i}"].value else "N/A" nom_nr = sheet[f"J{i}"].value if sheet[f"J{i}"].value else "N/A" kods = sheet[f"D{i}"].value if sheet[f"D{i}"].value else "N/A" pas_nr = sheet[f"K{i}"].value if sheet[f"K{i}"].value else "N/A" table_data_list.append({ "nos": nos, "nom_nr": nom_nr, "kods": kods, "pas_nr": pas_nr }) # 第二步:按每2个一组生成双列布局 # 分组处理数据 for idx in range(0, len(table_data_list), 2): # 创建一个1行2列的大表格,用来放两个小表格 container_table = doc.add_table(rows=1, cols=2) container_table.style = 'Table Grid' container_table.autofit = False container_table.alignment = WD_TABLE_ALIGNMENT.CENTER # 设置大表格的列宽,每个单元格刚好放下一个小表格 for cell in container_table.columns[0].cells: cell.width = Cm(8.0) # 2.5+5.5=8,加上少量边距 for cell in container_table.columns[1].cells: cell.width = Cm(8.0) # 处理第一个小表格 data1 = table_data_list[idx] table1 = container_table.cell(0, 0).add_table(rows=6, cols=2) table1.style = 'Table Grid' table1.autofit = False # 设置小表格列宽 for cell in table1.columns[0].cells: cell.width = Cm(2.5) for cell in table1.columns[1].cells: cell.width = Cm(5.5) # 填充数据 table1.cell(0, 0).text = "Nos." table1.cell(0, 1).text = str(data1["nos"]) table1.cell(1, 0).text = "Nom. Nr." table1.cell(1, 1).text = str(data1["nom_nr"]) table1.cell(2, 0).text = "Kods" table1.cell(2, 1).text = str(data1["kods"]) table1.cell(3, 0).text = "Pas. Nr." table1.cell(3, 1).text = str(data1["pas_nr"]) table1.cell(4, 0).text = "Daudzums" table1.cell(4, 1).text = "1000" table1.cell(5, 0).text = "Izpildītājs" table1.cell(5, 1).text = "SIA “STS Group”\nCeļāres 2B, Spilve, Babītes pag.\nTel. 29211780" # 处理第二个小表格(如果还有剩余数据) if idx + 1 < len(table_data_list): data2 = table_data_list[idx+1] table2 = container_table.cell(0, 1).add_table(rows=6, cols=2) table2.style = 'Table Grid' table2.autofit = False # 设置小表格列宽 for cell in table2.columns[0].cells: cell.width = Cm(2.5) for cell in table2.columns[1].cells: cell.width = Cm(5.5) # 填充数据 table2.cell(0, 0).text = "Nos." table2.cell(0, 1).text = str(data2["nos"]) table2.cell(1, 0).text = "Nom. Nr." table2.cell(1, 1).text = str(data2["nom_nr"]) table2.cell(2, 0).text = "Kods" table2.cell(2, 1).text = str(data2["kods"]) table2.cell(3, 0).text = "Pas. Nr." table2.cell(3, 1).text = str(data2["pas_nr"]) table2.cell(4, 0).text = "Daudzums" table2.cell(4, 1).text = "1000" table2.cell(5, 0).text = "Izpildītājs" table2.cell(5, 1).text = "SIA “STS Group”\nCeļāres 2B, Spilve, Babītes pag.\nTel. 29211780" # 每组之间添加空行 doc.add_paragraph("\n") # Save the Word document doc.save('data.docx')
关键修改点
- 数据预收集:先把所有需要生成的小表格数据存到列表里,方便后续分组处理
- 容器表格嵌套:用1行2列的大表格作为容器,每个单元格里嵌入原有的2列小表格,实现双列并排
- 宽度适配:调整容器表格的列宽,确保能容纳小表格,同时保持原小表格的列宽不变
- 分组逻辑:按步长2遍历数据列表,处理每组的1-2个小表格,避免最后一组数据不足时出错
内容的提问来源于stack exchange,提问作者GreyWanderer
相关产品推荐
相关产品推荐

