我有一个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")
“outputsheet”被指定引用wbOutput中的第一个(默认)工作表:
然后,主循环写入outputsheet,它总是引用同一个原始工作表,导致所有数据都出现在同一个工作表上:
^{pr2}$最简单的解决方案是放弃第三个内部循环,并使用get_sheet_by_name:
我现在不能测试代码,但总体思路应该行得通。在
编辑
尽管可能值得重新设计为类似于以下伪代码的代码:
相关问题 更多 >
编程相关推荐