Python中使用第三方库xlutils来追加写入Excel文件示例

yipeiwu_com5年前Python基础

目前还没有更好的方法来追写Excel,lorinnn在网上搜索到以及之后用到的方法就是使用第三方库xlutils来实现了这个功能,主体思想就是先复制一份Sheet然后再次基础上追加并保存到一份新的Excel文档中去。

使用xlutils

代码实现如下:

# -*- coding: utf-8 -*- 
''' 
Created on 2012-12-17 
 
@author: walfred 
@module: XLRDPkg.write_append 
@description: 
'''  
import os 
from xlutils.copy import copy 
import xlrd as ExcelRead 
 
def write_append(file_name): 
  values = ["Ann", "woman", 22, "UK"] 
 
  r_xls = ExcelRead.open_workbook(file_name) 
  r_sheet = r_xls.sheet_by_index(0) 
  rows = r_sheet.nrows 
  w_xls = copy(r_xls) 
  sheet_write = w_xls.get_sheet(0) 
 
  for i in range(0, len(values)): 
    sheet_write.write(rows, i, values[i]) 
 
  w_xls.save(file_name + '.out' + os.path.splitext(file_name)[-1]); 
 
if __name__ == "__main__": 
  write_append("./test_append.xls")

追写前

name sex  age country
jim  man  19 USA
hmm  woman 24 CHN
lilei man  24 CHN

追写后

name  sex  age country
jim  man  19 USA
hmm  woman 24 CHN
lilei man  24 CHN
Ann  woman 22 UK

相关文章

一篇文章读懂Python赋值与拷贝

一篇文章读懂Python赋值与拷贝

变量与赋值 在 Python 中,一切皆为对象,对象通过「变量名」引用,「变量名」更确切的叫法是「名字」,好比我们每个人都有自己的名字一样,咱们通过名字来代指某个人,代码里面通过名字来指...

Django框架之登录后自定义跳转页面的实现方法

Django auth 登陆后页面跳转至/account/profile,修改跳转至其他页面 这几天在学习django,django功能很强大,自带的auth,基本可以满足用户注册登陆登...

python list转置和前后反转的例子

python list转置和前后反转的例子

list/tuple转置: 以二维grid[][]为例: grid = [[row[i] for row in grid] for i in range(len(grid[0]))]...

python 实现tar文件压缩解压的实例详解

python 实现tar文件压缩解压的实例详解 压缩文件: import tarfile import os def tar(fname): t = tarfile.op...

pandas基于时间序列的固定时间间隔求均值的方法

pandas基于时间序列的固定时间间隔求均值的方法

如果index是时间序列就不用转datetime;但是如果时间序列是表中的某一列,可以把这一列设为index 例如: 代码: DF=df2.set_index(df1['time_...