Home>Article>Backend Development> Python implements copying method between excel worksheets
This article mainly introduces the method of copying between excel worksheets in python. It has a certain reference value. Now I share it with you. Friends in need can refer to
python. Copy Sheet1 of test1 to Sheet2 of test2 through "cross-file".
Including Google, no answer to this question can be found.
We post the code.
We load the openpyxl package to solve:
from openpyxl import load_workbook filename = 'test1.xlsx' filename2 = 'test2.xlsx' def replace_xls(sheetname): wb = load_workbook(filename) wb2 = load_workbook(filename2) ws = wb[sheetname] ws2 = wb2[sheetname] #两个for循环遍历整个excel的单元格内容 for i,row in enumerate(ws.iter_rows()): for j,cell in enumerate(row): ws2.cell(row=i+1, column=j+1, value=cell.value) wb2.save(filename2) sheetnames = [u'Sheet1',u'Sheet2',u'Sheet3',u'Sheet4'] #遇到复制几十个sheet时候,很有必要写个循环 for sheetname in sheetnames: replace_xls(sheetname)
Note that my code will overwrite the original content in excel.
If your excel is dynamic, you can write a vb script yourself, clear excel first and then run the python script.
Related recommendations:
Use python to implement XlsxWriter to create Excel files and edit them
The above is the detailed content of Python implements copying method between excel worksheets. For more information, please follow other related articles on the PHP Chinese website!