from openpyxl import Workbook,load_workbook
def copy_sheet(src_xlsx,ssheetname,dst_xlsx,nsheetname=None):
if nsheetname==None:
nsheetname=ssheetname
try:
sw=load_workbook(f'{src_xlsx}')
except KeyError:
raise KeyError('旧工作簿不存在 The old xlsx is not exists')
try:
dw=load_workbook(f'{dst_xlsx}')
except FileNotFoundError:
dw=Workbook()
try:
sheet = dw[f'{nsheetname}']
except KeyError:
sheet=dw.create_sheet(f'{nsheetname}')
try:
src_sheet=sw[f'{ssheetname}']
except KeyError:
raise KeyError('源工作簿文件不存在该工作簿 The sheet does not exist in the source file')
for row in src_sheet.iter_rows():
row_list=[]
for cell in row:
row_list.append(cell.value)
sheet.append(row_list)
dw.save(f'{dst_xlsx}')
使用说明:
src_xlsx 源Excel文件
ssheetname 源Excel文件中需要复制的sheet
dst_xlsx 目标Excel文件
nsheetname 目标Excel文件中复制后的sheet
注意:
上述函数只能复制内容,不能保留Excel中的格式,例如字体、背景色等。如果有需要保留原格式,请使用下面下一个函数。
代码解析:
该方法是从一个excel文件中读取数据,然后写到另一个excel文件中,写入语句为sheet.append(row_list)。前面的try-catch语句是为了处理文件不存在的异常。
一定记得保存操作(save)。
from openpyxl import load_workbook
workbook = load_workbook(filename="wb.xlsx")
sheet = workbook['Sheet1']
target = workbook.copy_worksheet(sheet)
workbook.save(filename="wb.xlsx")
使用说明:
"wb.xlsx"为Excel文件,根据需求改成需要复制的文件。
'Sheet1’为Excel中需要被复制的Sheet名字,可根据需求修改。
注意:
该方法可以将原sheet中的格式保留复制。
代码解析:
这个方法调用workbook.copy_worksheet()内置函数,sheet是要被复制的文本,一定要记得保存(save)操作!
复制的sheet的名字为‘原sheet名字 Copy’
当我们需要批量复制sheet时,对复制操作进行循环即可,但是当我们对sheet命名有要求时,会令人十分的头疼,因为workbook.copy_worksheet()内置函数不支持传入sheet名字参数。
于是我们查看workbook.copy_worksheet()的源码:
def copy_worksheet(self, from_worksheet):
"""Copy an existing worksheet in the current workbook
.. warning::
This function cannot copy worksheets between workbooks.
worksheets can only be copied within the workbook that they belong
:param from_worksheet: the worksheet to be copied from
:return: copy of the initial worksheet
"""
if self.__write_only or self._read_only:
raise ValueError("Cannot copy worksheets in read-only or write-only mode")
new_title = u"{0} Copy".format(from_worksheet.title)
to_worksheet = self.create_sheet(title=new_title)
cp = WorksheetCopy(source_worksheet=from_worksheet, target_worksheet=to_worksheet)
cp.copy_worksheet()
return to_worksheet
我们可以看到这一句:
new_title = u"{0} Copy".format(from_worksheet.title)
这句话的作用是给sheet命名,可以看到命名规则为:“被复制的sheet名字 Copy”
当我们对所复制的命名有要求是,可以修改这行代码,也可以直接修改函数,给函数添加一个sheet名字的参数:
def copy_worksheet(self, from_worksheet,sheet_name):
"""Copy an existing worksheet in the current workbook
.. warning::
This function cannot copy worksheets between workbooks.
worksheets can only be copied within the workbook that they belong
:param from_worksheet: the worksheet to be copied from
:return: copy of the initial worksheet
"""
if self.__write_only or self._read_only:
raise ValueError("Cannot copy worksheets in read-only or write-only mode")
#new_title = u"{0} Copy".format(from_worksheet.title)
new_title = sheet_name
to_worksheet = self.create_sheet(title=new_title)
cp = WorksheetCopy(source_worksheet=from_worksheet, target_worksheet=to_worksheet)
cp.copy_worksheet()
return to_worksheet
可以看到我在copy_worksheet()函数中添加了一个sheet_name的参数,并将其赋值给new_title。
将example.xlsx中的Sheet1复制300次,命名为"0#"、“1#”、“2#”…“299#”。
from openpyxl import load_workbook
workbook = load_workbook(filename="example.xlsx")
sheet = workbook['Sheet1']
for i in range(300):
sheet_name="{0}#".format(i)
target = workbook.copy_worksheet(sheet,sheet_name)
workbook.save(filename="example.xlsx")