如何在 Python 中将 Excel 工作表复制到另一个工作簿
- 2025-04-10 09:45:00
- admin 原创
- 24
问题描述:
我有一个带有源文件路径的字符串和另一个带有目标文件路径的字符串,它们都指向 Excel 工作簿。
我想取出源文件的第一张表并将其作为新选项卡复制到目标文件(无论目标文件中的什么位置),然后保存它。
找不到简单的方法来xlrd
执行xlwt
此xlutils
操作。我遗漏了什么吗?
解决方案 1:
解决方案 1
使用该包的仅限 Python 的解决方案openpyxl
。仅复制数据值。
import openpyxl as xl
path1 = 'C:\\Users\\Xukrao\\Desktop\\workbook1.xlsx'
path2 = 'C:\\Users\\Xukrao\\Desktop\\workbook2.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)
解决方案 2
使用包将复制操作委托给 Excel 应用程序的解决方案pywin32
。数据值、格式和工作表中的所有其他内容都将被复制。注意:此解决方案仅适用于安装了 MS Excel 的 Windows 计算机。
from win32com.client import Dispatch
path1 = 'C:\\Users\\Xukrao\\Desktop\\workbook1.xlsx'
path2 = 'C:\\Users\\Xukrao\\Desktop\\workbook2.xlsx'
xl = Dispatch("Excel.Application")
xl.Visible = True # You can remove this line if you don't want the Excel application to be visible
wb1 = xl.Workbooks.Open(Filename=path1)
wb2 = xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))
wb1.Close(SaveChanges=False)
wb2.Close(SaveChanges=True)
xl.Quit()
解决方案 3
使用包将复制操作委托给 Excel 应用程序的解决方案xlwings
。Xlwings 本质上是 (大多数,但不是全部) pywin32
/ appscript
excel API 函数的智能包装器。数据值、格式和工作表中的所有其他内容都会被复制。注意:此解决方案仅适用于安装了 MS Excel 的 Windows 或 Mac 计算机。
import xlwings as xw
path1 = 'C:\\Users\\Xukrao\\Desktop\\workbook1.xlsx'
path2 = 'C:\\Users\\Xukrao\\Desktop\\workbook2.xlsx'
wb1 = xw.Book(path1)
wb2 = xw.Book(path2)
ws1 = wb1.sheets(1)
ws1.api.Copy(Before=wb2.sheets(1).api)
wb2.save()
wb2.app.quit()
解决方案 2:
如果你不反对使用 Pandas,这可能会有所帮助
import pandas as pd
#change xxx with the sheet name that includes the data
data = pd.read_excel(sourcefile, sheet_name="xxx")
#save it to the 'new_tab' in destfile
data.to_excel(destfile, sheet_name='new_tab')
希望有帮助
解决方案 3:
您也可以尝试xlwings。
import xlwings as xw
wb = xw.Book(r'C:path oile.xlsx')
sht = wb.sheets['Sheet1']
new_wb = xw.Book(r'C:
ew_path oile.xlsx')
new_wb.sheets['name'] = sht
解决方案 4:
解决方案 1 是唯一适用于 Linux 的方法,因此适合服务器自动化。然而,Openpyxl 仅保留包含模板中数据的单元格的格式。
因此,openpyxl 需要在模板中进行一些调整:用空格(“ ”)填充模板中所有可能稍后填充的单元格。对数百万行执行此操作将使 Excel 爆炸,但处理数千行的数据变化效果相当好。并且“ ”在大多数情况下是不可见的,如果填充的行较少,则不会引起任何问题。相比之下,其他虚拟数据可能会。
解决方案 5:
我只是尝试了一下,因为我们的场景有 2 个单独的工作表。但我们也可以将此代码片段用于其他场景,例如创建新工作表,然后将数据也提供给新工作表。
def sheet_copy(source_file, target_file, sheet_idx):
wb1 = openpyxl.load_workbook(filename=source_file)
ws1 = wb1.worksheets[sheet_idx]
wb2 = openpyxl.load_workbook(filename=target_file)
ws2 = wb2.create_sheet(ws1.title)
for row in ws1:
for cell in row:
ws2[cell.coordinate].value = cell.value
wb2.save(source_file)
现在,创建方法后,我们也可以将任何所需的工作表从源工作簿添加到目标工作簿。
sheet_copy(base_file_path, output_file, 0)
这base_file_path
是我们要从中提取所需工作表的源文件。output_file
是我在此操作之前创建的文件。因此,在确认源和目标之后,我们需要添加将被复制的工作表索引。所以索引在0
这里。
解决方案 6:
此功能的工作方式类似于将工作表移动至其他工作簿。
from openpyxl import load_workbook, Workbook
from copy import copy
def copy_worksheet(source_path, source_sheet_name, destination_path):
"""
Copies a worksheet from a source workbook to a destination workbook, including row heights, merged cells,
and only pasting values for formula cells, with gridlines removed in the destination sheet.
Parameters:
- source_path: Path to the source workbook (str).
- source_sheet_name: Name of the sheet to copy from the source workbook (str).
- destination_path: Path to the destination workbook (str).
"""
# Load the source workbook and the specified sheet
source_workbook = load_workbook(source_path, data_only=True) # Load formulas as values
source_sheet = source_workbook[source_sheet_name]
# Load or create the destination workbook
try:
destination_workbook = load_workbook(destination_path)
except FileNotFoundError:
destination_workbook = Workbook()
# Create a new sheet in the destination workbook with the same title as the source sheet
destination_sheet = destination_workbook.create_sheet(title=source_sheet.title)
destination_sheet.sheet_view.showGridLines = False # Remove gridlines in the copied sheet
# Copy cell values, styles, row heights, and merged cells from the source sheet to the destination sheet
for row in source_sheet.iter_rows():
# Set row height
destination_sheet.row_dimensions[row[0].row].height = source_sheet.row_dimensions[row[0].row].height
for cell in row:
# Copy value only (not formula)
new_cell = destination_sheet.cell(row=cell.row, column=cell.column, value=cell.value)
# Copy each cell's style attributes safely
if cell.has_style:
new_cell.font = copy(cell.font)
new_cell.border = copy(cell.border)
new_cell.fill = copy(cell.fill)
new_cell.number_format = cell.number_format
new_cell.protection = copy(cell.protection)
new_cell.alignment = copy(cell.alignment)
# Copy merged cells
for merged_range in source_sheet.merged_cells.ranges:
destination_sheet.merge_cells(str(merged_range))
# Save the changes to the destination workbook
destination_workbook.save(destination_path)
print(f"Worksheet '{source_sheet_name}' copied from '{source_path}' to '{destination_path}'")
# Example usage
copy_worksheet('source_workbook.xlsx', 'Sheet1', 'destination_workbook.xlsx')
解决方案 7:
经过一番苦战,终于找到了答案。来自 xlwings 源代码:https://github.com/xlwings/xlwings/pull/1216/files
source_sheet.range.copy(destination_sheet.range)
换句话说:
wb.sheets['Sheet1'].range('A1:A6').copy(wb.sheets['Sheet2'].range('A1:A6'))
它也可以从一个工作簿运行到另一个工作簿。
必须提供单元格范围。只需确保范围足够大以覆盖整个工作表即可。
复制功能可复制/粘贴单元格范围内的所有内容(值、单元格格式、超链接、单元格类型等)
扫码咨询,免费领取项目管理大礼包!