使用Openpyxl将工作表从一个工作簿复制到另一个工作簿

时间:2017-02-20 12:00:19

标签: excel python-3.x copy openpyxl worksheet

我有大量的EXCEL文件(即200个)我想将一个特定的工作表从一个工作簿复制到另一个工作簿。我做了一些调查,我找不到使用Openpyxl

的方法

这是我目前开发的代码

$user->roles

有什么建议吗?

干杯

5 个答案:

答案 0 :(得分:2)

您不能使用copy_worksheet()在工作簿之间进行复制,因为它取决于工作簿之间可能不同的全局常量。唯一安全可靠的方法是逐行和逐个单元地进行。

您可能需要阅读discussions about this feature

答案 1 :(得分:1)

我有类似的要求将多个工作簿中的数据整理到一个工作簿中。由于openpyxl中没有可用的内置方法。

我创建了以下脚本来为我完成这项工作。

注意:在我的用例中,所有工作簿都包含相同格式的数据。

from openpyxl import load_workbook
import os


# The below method is used to read data from an active worksheet and store it in memory.
def reader(file):
    global path
    abs_file = os.path.join(path, file)
    wb_sheet = load_workbook(abs_file).active
    rows = []
    # min_row is set to 2, to ignore the first row which contains the headers
    for row in wb_sheet.iter_rows(min_row=2):
        row_data = []
        for cell in row:
            row_data.append(cell.value)
        # custom column data I am adding, not needed for typical use cases
        row_data.append(file[17:-6])
        # Creating a list of lists, where each list contain a typical row's data
        rows.append(row_data)
    return rows


if __name__ == '__main__':
    # Folder in which my source excel sheets are present
    path = r'C:\Users\tom\Desktop\Qt'
    # To get the list of excel files
    files = os.listdir(path)
    for file in files:
        rows = reader(file)
        # below mentioned file name should be already created
        book = load_workbook('new.xlsx')
        sheet = book.active
        for row in rows:
            sheet.append(row)
        book.save('new.xlsx')

答案 2 :(得分:1)

我刚刚发现了这个问题。如上所述here,一个好的解决方法可能包括修改内存中的原始wb并使用其他名称保存它。例如:

import openpyxl

# your starting wb with 2 Sheets: Sheet1 and Sheet2
wb = openpyxl.load_workbook('old.xlsx')

sheets = wb.sheetnames # ['Sheet1', 'Sheet2']

for s in sheets:

    if s != 'Sheet2':
        sheet_name = wb.get_sheet_by_name(s)
        wb.remove_sheet(sheet_name)

# your final wb with just Sheet1
wb.save('new.xlsx')

答案 3 :(得分:0)

我使用的解决方法是将当前工作表保存为pandas数据框并将其加载到您需要的Excel工作簿中

答案 4 :(得分:0)

我的解决方法如下:

您有一个模板文件,假设它是“ template.xlsx”。 您打开它,根据需要对其进行更改,将其另存为新文件,然后关闭该文件。 根据需要重复。测试/发送消息时,只需确保保留原始模板的副本即可。