Python/Pandas 从 Excel 表复制和粘贴

新手上路,请多包涵

我发现这种语法可以从一个工作簿特定的工作表复制并粘贴到另一个工作簿。但是,我需要帮助的是如何将复制的信息粘贴到第二个工作簿/工作表中的特定单元格。就像我需要将信息粘贴到单元格 B3 而不是 A1 中一样。谢谢

import openpyxl as xl
path1 = "C:/Users/almur_000/Desktop/disandpopbyage.xlsx"
path2 = "C:/Users/almur_000/Desktop/disandpopbyage2.xlsx"
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]
wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.create_sheet(ws1.title)
for row in ws1:
    for cell in row:
        ws2[cell.coordinate].value = cell.value
wb2.save(path2)

wb2 是路径 2“C:/Users/almur_000/Desktop/disandpopbyage2.xlsx”

原文由 Mazin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
1 个回答

由于 OP 使用 openpyxl 模块,我想展示一种使用该模块执行此操作的方法。通过这个答案,我演示了一种将原始数据移动到新的列和行坐标的方法(可能有更好的方法来做到这一点)。

这个完全可重现的示例首先创建了一个名为“test.xlsx”的用于演示目的的工作簿,其中包含三个名为“test_1”、“test_2”和“test_3”的工作表。然后使用 openpyxl ,它将“test_2”复制到一个名为“new.xlsx”的新工作簿中,将单元格移动 4 列并向下移动 3 列。它利用了 ord()chr() 功能。

 import pandas as pd
import numpy as np
import openpyxl

# This section is sample code that creates a worbook in the current directory with 3 worksheets
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='test_1', index=False)
df.to_excel(writer, sheet_name='test_2', index=False)
df.to_excel(writer, sheet_name='test_3', index=False)
wb  = writer.book
ws = writer.sheets['test_2']
writer.close()
# End of sample code that creates a worbook in the current directory with 3 worksheets

wb = openpyxl.load_workbook('test.xlsx')
ws_name_wanted = "test_2"
list_all_ws = wb.get_sheet_names()
for item in list_all_ws:
    if item != ws_name_wanted:
        remove = wb.get_sheet_by_name(item)
        wb.remove_sheet(remove)
ws = wb['%s' % (ws_name_wanted)]
for row in ws.iter_rows():
    for cell in row:
        cell_value = cell.value
        new_col_loc = (chr(int(ord(cell.coordinate[0:1])) + 4))
        new_row_loc = cell.coordinate[1:]
        ws['%s%d' % (new_col_loc ,int(new_row_loc) + 3)] = cell_value
        ws['%s' % (cell.coordinate)] = ' '

 wb.save("new.xlsx")

这是“test.xlsx”的样子:

test.xlsx 的预期输出

这是“new.xlsx”的样子:

new.xlsx 的预期输出

原文由 patrickjlong1 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题