gpt4 book ai didi

python - 使用 Openpyxl 在 excel 中复制和重新排列列

转载 作者:行者123 更新时间:2023-12-04 20:56:51 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Copy paste column range using OpenPyxl

(1 个回答)


4年前关闭。




我在 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)

我想创建一个循环来完成其余的工作,但我不知道如何设计它,这样我就不必为每一列编码和设置。

最佳答案

好吧,您可以回收代码,执行以下操作:

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)

告诉我这是否适合你

关于python - 使用 Openpyxl 在 excel 中复制和重新排列列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45925316/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com