首页 > 解决方案 > 带有枚举的 for 循环迭代 4 次,但只有 1 个数据帧被写入 Excel,而不是 4 个数据帧

问题描述

我整天都在为这段代码苦苦挣扎。在循环的每次运行期间,都会从不同的 MS Word 文件中读取一个表。该表被复制到数据框,然后被复制到 Excel 文件中的一行。

随着 for 循环的每次后续运行,Excel 行会递增,因此可以将新数据帧写入新行,但在文件执行后,只有一行显示数据帧。

当我打印(tfile)时,我得到以下..('CIV-ASCS-016_TRS.docx','CIV-ASCS-018_TRS .docx','CIV-ASCS-020_TRS.docx','CIV-ASCS-021_TRS .docx') 这证明循环基于目录中的 4 个文件运行了 4 次。我在 for 循环之外将初始行 pos 设置为 0。

注意:关于导入必要的库,我没有显示任何代码行。

files = glob('*.docx')
pos = 1

for i, wfile in enumerate(files[:1]):

  document = Document(wfile)

  table = document.tables[0]
  data = []
  keys = {}

  for j, row in enumerate(table.rows):
     text = (cell.text for cell in row.cells)
     if j == 0:
            keys = tuple(text)
            continue

     row_data = dict(zip(keys, text))
     data.append(row_data)

     tfile = tuple(files)

  df = pd.DataFrame(data)
  df.loc[-1] = [wfile, 'Test Case ID']   
  df.index = df.index + 1  # shifting index
  df = df.sort_index()  # sorting by index

  df1 = df.rename(index=str, columns={"Test Case ID": "TC Attributes"})

  df21 = df1.drop(columns = ['TC Attributes'])
  df3 = df21.T

# read the existing sheets so that openpyxl won't create a new one later
  book = load_workbook('test.xlsx')
  writer = pd.ExcelWriter('test.xlsx', engine='openpyxl') 
  writer.book = book
  writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
  df3.to_excel(writer, 'sheet7', header = False, index = False, \
             startrow = pos)
  pos += 1

  writer.save()

标签: pythonpandasopenpyxl

解决方案


推荐阅读