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

标签 python excel formatting copy-paste openpyxl

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





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/

相关文章:

python - 无法连接 MySQL 和 Python

c++ - boost::format 和 wchar_t

java - Android 货币格式返回不同的货币符号

python - 选择基于 where 语句的行

python - 使用 BeautifulSoup4 在 sibling 子树中查找

excel - 书面 excel 测验中的多个正确答案

Excel VBA 到 Word 取消选择选定的文本

mysql - Excel 2016 在数据中连接到 MySQL 从数据库进行新查询

c# - 寻找适用于 C# 代码的可配置 pretty-print

python - 是否可以在 Python 2 中使用 'print >>' 而不使用换行符和空格?