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

时间:2022-06-19 02:58:30

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

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

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

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

?
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
26
27
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中新增表,不覆盖原数据的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xxzhix/article/details/79324554