网络编程
位置:首页>> 网络编程>> Python编程>> python向已存在的excel中新增表,不覆盖原数据的实例

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

作者:xxzhix  发布时间:2022-04-26 15:16:51 

标签:python,excel,新增,表,覆盖

每月需更新某个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)

来源:https://blog.csdn.net/xxzhix/article/details/79324554

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com