您的位置:首页 > 编程语言 > Python开发

python向已存在的excel中新增表,不覆盖原数据的实例

2018-05-02 14:52 756 查看

每月需更新某个excel表格,进行两项操作,且不覆盖原有的sheet:

1. 在原来的excel表中新增sheet

2. 往原有的excel表中的某张sheet新增内容

基于python3,使用xlrd,xlwt,具体代码如下,亲测有效,希望对大家有帮助,谢谢!

import xlwt
import xlrd
from xlutils.copy import copy
#打开需要操作的excel表
wb=xlrd.open_workbook(path)
#复制原有表
newb=copy(wb)
#新增sheet,参数是该sheet的名字,可自定义
wbsheet=newb.add_sheet(dl+'-'+dn)
#向新sheet中写入数据。本代码中的d是某个dataframe
wbsheet.write(0,0,'date')
wbsheet.write(0,1,'visited')
wbsheet.write(0,2,'success')
for i in range(d.shape[0]):
wbsheet.write(i + 1, 0, d.iloc[i, 0])
for j in range(1,d.shape[1]):
wbsheet.write(i+1,j,int(d.iloc[i,j]))
#获取原有excel表中sheet名为‘summary'的sheet
sumsheet=newb.get_sheet('summary')
#k表示该sheet的最后一行
k=len(sumsheet.rows)
#想原有sheet后面新增数据
sumsheet.write(k,0,dl+'-'+dn)
sumsheet.write(k,1,int(sum(d['visited'])))
sumsheet.write(k,2,int(sum(d['success'])))
#保存为原有的excel表路径
newb.save(path)

以上这篇python向已存在的excel中新增表,不覆盖原数据的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python excel 新增 覆盖