我在excel文件中有数据,但为了它有用,我需要复制&将列粘贴到不同的顺序。 我已经想出了如何打开&读取我的文件并编写一个新的excel文件。我也可以从原始数据中获取数据,然后将其粘贴到我的新文件中,但不能将其粘贴到循环中。
here's an example of the data i'm working with to visualize my issue我需要A1,B1,C1彼此相邻,然后是A2,B2,C2等等。
以下是我创建的一个较小的测试文件的代码:
import openpyxl as op
wb = op.load_workbook('coding_test.xlsx')
ws = wb.active
mylist = []
mylist2 = []
mylist3 = []
for row in ws.iter_rows('H13:H23'):
for cell in row:
mylist.append(cell.value)
for row in ws.iter_rows('L13:L23'):
for cell in row:
mylist2.append(cell.value)
for row in ws.iter_rows('P13:P23'):
for cell in row:
mylist3.append(cell.value)
print (mylist, mylist2, mylist3)
new_wb = op.Workbook()
dest_filename = 'empty_coding_test.xlsx'
new_ws = new_wb.active
for row in zip (mylist, mylist2, mylist3):
new_ws.append(row)
new_wb.save(filename=dest_filename)
我想创建一个循环来完成剩下的工作,但是我无法弄清楚如何设计它以便我不必编写每列的代码并进行设置。
答案 0 :(得分:-1)
好吧,您可以通过以下方式回收代码:
import openpyxl as op
wb = op.load_workbook('coding_test.xlsx')
ws = wb.active
new_wb = op.Workbook()
dest_filename = 'empty_coding_test.xlsx'
new_ws = new_wb.active
for row in ws.iter_rows('H13:H23'):
for cell in row:
new_ws['A%s' % cell].value = cell.value
for row in ws.iter_rows('L13:L23'):
for cell in row:
new_ws['B%s' % cell].value = cell.value
for row in ws.iter_rows('P13:P23'):
for cell in row:
new_ws['C%s' % cell].value = cell.value
new_wb.save(filename=dest_filename)
告诉我你的工作是否合适