迭代工作表,为每次迭代添加数据

2024-09-28 19:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

Input FileOutput FIle

我有一个excel文件,其中所有的数据都列在行中(第一张图片),我需要将这些数据列在新创建的工作簿中各个工作表的A列中(需要看起来像第二张图像)。我为每个问题都写了单独的数据表。我的代码现在把这些数据都写在同一个工作表上。在

import openpyxl
import os
import time

wb = openpyxl.load_workbook('IP-Results.xlsx') #load input file
sheet = wb.get_sheet_by_name('IP-Results-32708') #get sheet from input file

wbOutput = openpyxl.Workbook() #open a new workbook
wbOutput.remove_sheet(wbOutput.get_sheet_by_name('Sheet')) #remove initial worksheet named 'sheet'

for cell in sheet['A']: #iterate through firewall names in column A and make those the title of the sheets in new workbook
    value = cell.value
    wbOutput.create_sheet(title=cell.value)

inputwb = wb
inputsheet = inputwb.active
outputwb = wbOutput
outputsheet = outputwb.active
maxRow = inputsheet.max_row
maxCol = inputsheet.max_column

for i in range(1, max(maxRow, maxCol) +1):
    for j in range(1, min(maxRow, maxCol) + 1):
        for sheet in outputwb.get_sheet_names():
            outputsheet.cell(row=i, column=j).value  = inputsheet.cell(row=j, column=i).value
            outputsheet.cell(row=j, column=i).value  = inputsheet.cell(row=i, column=j).value

wbOutput.save("Decom-" + time.strftime("%m-%d-%Y")+ ".xlsx")

Tags: 数据inimportforgetvaluecellcolumn
1条回答
网友
1楼 · 发布于 2024-09-28 19:21:35

“outputsheet”被指定引用wbOutput中的第一个(默认)工作表:

outputwb = wbOutput
outputsheet = outputwb.active

然后,主循环写入outputsheet,它总是引用同一个原始工作表,导致所有数据都出现在同一个工作表上:

^{pr2}$

最简单的解决方案是放弃第三个内部循环,并使用get_sheet_by_name:

for i in range(1, max(maxRow, maxCol) +1):
        sheet_name = inputsheet.cell(row=i, column=1).value
        a_sheet = outputwb .get_sheet_by_name(sheet_name)
        for j in range(1, min(maxRow, maxCol) + 1):
            a_sheet.cell(row=i, column=1).value  = inputsheet.cell(row=j, column=i).value

我现在不能测试代码,但总体思路应该行得通。在

编辑

尽管可能值得重新设计为类似于以下伪代码的代码:

for each inputwb_row in inputworkbook:
    new_sheet = create a new_sheet in outputworkbook
    set new_sheet.title = inputworkbook.cell[row,1].value
    for each column in inputwb_row:
        new_sheet.cell[column, 1].value =  inputworkbook.cell[inputwb_row ,column].value 

相关问题 更多 >