您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python如何将指定工作表批量复制到指定工作表
## 前言
在日常办公自动化处理中,我们经常需要对Excel文件中的工作表进行批量操作。本文将详细介绍如何使用Python的`openpyxl`和`xlwings`库实现将指定工作表批量复制到目标工作表的操作,包含完整代码示例和实际应用场景分析。
---
## 一、准备工作
### 1.1 安装必要库
```bash
pip install openpyxl xlwings
from openpyxl import load_workbook
def copy_sheets_openpyxl(source_file, target_file, sheet_names):
"""
使用openpyxl复制指定工作表
:param source_file: 源文件路径
:param target_file: 目标文件路径
:param sheet_names: 需要复制的工作表名称列表
"""
# 加载工作簿
source_wb = load_workbook(source_file)
target_wb = load_workbook(target_file)
for sheet_name in sheet_names:
# 复制工作表
source_sheet = source_wb[sheet_name]
new_sheet = target_wb.create_sheet(title=f"{sheet_name}_Copy")
# 复制单元格数据
for row in source_sheet.iter_rows():
for cell in row:
new_sheet[cell.coordinate].value = cell.value
# 保存目标工作簿
target_wb.save(target_file)
print(f"成功复制 {len(sheet_names)} 个工作表")
# 使用示例
copy_sheets_openpyxl(
source_file="source.xlsx",
target_file="target.xlsx",
sheet_names=["Sheet1", "Sheet2"]
)
from openpyxl.utils import get_column_letter
def copy_with_format(source_sheet, target_sheet):
# 复制列宽
for col in range(1, source_sheet.max_column + 1):
col_letter = get_column_letter(col)
target_sheet.column_dimensions[col_letter].width = \
source_sheet.column_dimensions[col_letter].width
# 复制行高
for row in range(1, source_sheet.max_row + 1):
target_sheet.row_dimensions[row].height = \
source_sheet.row_dimensions[row].height
# 复制样式
for row in source_sheet.iter_rows():
for cell in row:
target_sheet[cell.coordinate].font = cell.font.copy()
target_sheet[cell.coordinate].border = cell.border.copy()
target_sheet[cell.coordinate].fill = cell.fill.copy()
target_sheet[cell.coordinate].number_format = cell.number_format
target_sheet[cell.coordinate].alignment = cell.alignment.copy()
import xlwings as xw
def copy_sheets_xlwings(source_path, target_path, sheet_names):
"""
使用xlwings复制指定工作表(需要安装Excel)
:param source_path: 源文件路径
:param target_path: 目标文件路径
:param sheet_names: 需要复制的工作表名称列表
"""
app = xw.App(visible=False) # 不可见模式
try:
source_wb = app.books.open(source_path)
target_wb = app.books.open(target_path)
for sheet_name in sheet_names:
source_sheet = source_wb.sheets[sheet_name]
new_sheet = target_wb.sheets.add(
name=f"{sheet_name}_Copy",
after=target_wb.sheets[-1]
)
source_sheet.api.Copy(Before=new_sheet.api)
new_sheet.name = f"{sheet_name}_Copy" # 重命名避免冲突
target_wb.save()
print(f"成功复制 {len(sheet_names)} 个工作表")
finally:
app.quit()
# 使用示例
copy_sheets_xlwings(
source_path="source.xlsx",
target_path="target.xlsx",
sheet_names=["Data", "Report"]
)
with
语句管理资源app = xw.App(visible=False)
app.screen_updating = False
# 执行复制操作...
app.screen_updating = True
# 将12个月份的工作表合并到年度总表
monthly_sheets = [f"{month}月" for month in range(1, 13)]
copy_sheets_openpyxl(
source_file="2023年度数据.xlsx",
target_file="年度总报表.xlsx",
sheet_names=monthly_sheets
)
# 基于模板生成多部门报表
departments = ["销售部", "技术部", "财务部"]
template_sheets = ["数据模板", "分析模板"]
for dept in departments:
copy_sheets_xlwings(
source_path="公司模板.xlsx",
target_path=f"{dept}报告.xlsx",
sheet_names=template_sheets
)
# 自动重命名逻辑示例
import re
def get_unique_name(target_wb, base_name):
existing_names = [sheet.name for sheet in target_wb.worksheets]
if base_name not in existing_names:
return base_name
# 处理重复名称(如:Sheet1_Copy(2))
pattern = re.compile(rf"^{base_name}_Copy(?:\((\d+)\))?$")
max_num = 0
for name in existing_names:
match = pattern.match(name)
if match:
num = int(match.group(1)) if match.group(1) else 1
max_num = max(max_num, num)
return f"{base_name}_Copy({max_num + 1})"
read_only
模式读取源文件source_wb = load_workbook(source_file, read_only=True)
target_wb = load_workbook(target_file)
本文详细介绍了两种Python实现Excel工作表批量复制的方法,读者可以根据实际需求选择:
- openpyxl
:纯Python解决方案,适合简单操作
- xlwings
:依赖Excel但功能更强大
完整代码示例已提供,建议根据实际业务需求进行适当修改。更多高级功能可参考官方文档进一步探索。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。