循环写入Excel避免内容覆盖:多Word表格数据逐行写入同工作表需求
批量Word表格数据写入Excel时保留所有行的解决方案
问题原因
你的代码每次循环执行df.to_excel(writer, sheet_name='Sheet1')时,默认会从工作表第0行开始写入,直接覆盖之前的内容,最终仅保留最后一次循环的数据。
解决方案(推荐:先收集所有数据再统一写入)
先创建一个空的总DataFrame,每次从Word中提取到目标行数据后,将其追加到总DataFrame中,最后一次性写入Excel,避免重复覆盖。
修改后的完整代码:
import os import pandas as pd from docx import Document path = 'folder path' worddocs_list = [] for filename in os.listdir(path): # 过滤非docx文件,避免读取报错 if filename.endswith('.docx'): wordDoc = Document(os.path.join(path, filename)) worddocs_list.append(wordDoc) # 初始化总DataFrame,指定固定列名 total_df = pd.DataFrame(columns=[f'Column_{i}' for i in range(6)]) for wordDoc in worddocs_list: for table in wordDoc.tables: row_lst = [] # 提取指定行和列的内容 for row in table.rows[5:6]: for cell in row.cells[1:7]: row_lst.append(cell.text) # 将单条数据转为DataFrame并追加到总表 single_df = pd.DataFrame([row_lst], columns=[f'Column_{i}' for i in range(6)]) total_df = pd.concat([total_df, single_df], ignore_index=True) # 统一写入Excel文件 with pd.ExcelWriter("./test.xlsx", engine='xlsxwriter') as writer: total_df.to_excel(writer, sheet_name='Sheet1', index=False)
关键改动说明
- 提前初始化带指定列名的
total_df,用于存储所有提取到的数据 - 简化单条数据的DataFrame构造逻辑,替代原有的循环赋值操作
- 使用
pd.concat追加数据,ignore_index=True保证索引连续不重复 - 仅在最后调用一次
to_excel,一次性写入所有数据,彻底避免覆盖问题 - 增加文件格式过滤和
os.path.join路径拼接,提升代码兼容性和稳定性
备选方案:逐行写入指定起始行
如果不想提前收集所有数据,也可以通过startrow参数指定每次写入的起始位置:
import os import pandas as pd from docx import Document path = 'folder path' worddocs_list = [] for filename in os.listdir(path): if filename.endswith('.docx'): wordDoc = Document(os.path.join(path, filename)) worddocs_list.append(wordDoc) writer = pd.ExcelWriter("./test.xlsx", engine='xlsxwriter') start_row = 0 # 记录当前写入的起始行号 for wordDoc in worddocs_list: for table in wordDoc.tables: row_lst = [] for row in table.rows[5:6]: for cell in row.cells[1:7]: row_lst.append(cell.text) single_df = pd.DataFrame([row_lst], columns=[f'Column_{i}' for i in range(6)]) # 第一次写入时保留表头,后续跳过表头 single_df.to_excel(writer, sheet_name='Sheet1', index=False, startrow=start_row, header=(start_row == 0)) start_row += 1 writer.save()
内容的提问来源于stack exchange,提问作者lalala
相关产品推荐
相关产品推荐

