码迷,mamicode.com
首页 > 编程语言 > 详细

python实现跨excel的工作表sheet之间的复制

时间:2018-07-17 00:44:38      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:python实现   data   otto   ace   target   rom   data-   href   com   

百度搜索问题:python复制Excel中的sheet到另外一个工作簿

其中一篇文章:

地址:https://blog.csdn.net/lingan_hong/article/details/72765116

python实现跨excel的工作表sheet之间的复制

python,将test1的Sheet1通过“跨文件”复制到test2的Sheet2里面。

包括谷歌没有能搜出这种问题答案。 
我们贴出代码。

我们加载openpyxl这个包来解决:

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

注意,我的代码会覆盖掉本来excel中的内容。 
如何你的excel是动态的,可以自己写一个vb脚本,先清空excel再去运行python脚本。

最后,请参考openpyxl这个包的文档: 
https://media.readthedocs.org/pdf/openpyxl/latest/openpyxl.pdf

 

python实现跨excel的工作表sheet之间的复制

标签:python实现   data   otto   ace   target   rom   data-   href   com   

原文地址:https://www.cnblogs.com/gonghongwei/p/9321207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!