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

yipeiwu_com6年前Python基础

每月需更新某个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设计】。

相关文章

对matplotlib改变colorbar位置和方向的方法详解

如下所示: #! usr/bin/python #coding=utf-8 import numpy as np import matplotlib.pyplot as plt...

创建Shapefile文件并写入数据的例子

创建Shapefile文件并写入数据的例子

基本思路 使用GDAL创建Shapefile数据的基本步骤如下: 使用osgeo.ogr.Driver的CreateDataSource()方法创建osgeo.ogr.DataSourc...

python中redis查看剩余过期时间及用正则通配符批量删除key的方法

具体代码如下所示: # -*- coding: utf-8 -*- import redis import datetime ''' # 1. redis设置过期时间的两种方式 e...

python 连接各类主流数据库的实例代码

本篇博文主要介绍Python连接各种数据库的方法及简单使用 包括关系数据库:sqlite,mysql,mssql 非关系数据库:MongoDB,Redis 代码写的比较清楚,直接上代码...

python中django框架通过正则搜索页面上email地址的方法

本文实例讲述了python中django框架通过正则搜索页面上email地址的方法。分享给大家供大家参考。具体实现方法如下: import re from django.shortc...