Home > Backend Development > Python Tutorial > Python implements copying method between excel worksheets

Python implements copying method between excel worksheets

不言
Release: 2018-05-04 16:02:54
Original
6624 people have browsed it

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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template