Python读写/追加excel文件Demo

来源:互联网 发布:中医 数据库 编辑:程序博客网 时间:2024/06/05 10:56

转自:http://blog.csdn.net/qq_30242609/article/details/68953172


三个工具包

Python操作excel的三个工具包如下,注意,只能操作.xls,不能操作.xlsx

  • xlrd: 对excel进行读相关操作
  • xlwt: 对excel进行写相关操作
  • xlutils: 对excel读写操作的整合

这三个工具包都可以直接使用pip进行下载:

sudo pip install xlrdsudo pip install xlwtsudo pip install xlutils
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

xlwt的缺陷

xlwt只能创建一个全新的excel文件,然后对这个文件进行写入内容以及保存。但是大多数情况下我们希望的是读入一个excel文件,然后进行修改或追加,这个时候就需要xlutils了。

xlutils的简单使用

下面的demo是给一个excel文件追加内容:

#coding:utf-8from xlrd import open_workbookfrom xlutils.copy import copyrexcel = open_workbook("collection.xls") # 用wlrd提供的方法读取一个excel文件rows = rexcel.sheets()[0].nrows # 用wlrd提供的方法获得现在已有的行数excel = copy(rexcel) # 用xlutils提供的copy方法将xlrd的对象转化为xlwt的对象table = excel.get_sheet(0) # 用xlwt对象的方法获得要操作的sheetvalues = ["1", "2", "3"]row = rowsfor value in values:    table.write(row, 0, value) # xlwt对象的写方法,参数分别是行、列、值    table.write(row, 1, "haha")    table.write(row, 2, "lala")    row += 1excel.save("collection.xls") # xlwt对象的保存方法,这时便覆盖掉了原来的excel
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

相关文档

  • xlrd:http://xlrd.readthedocs.io/en/latest/
  • xlwt:http://xlwt.readthedocs.io/en/latest/
  • xlutils:http://xlutils.readthedocs.io/en/latest/index.html

原创粉丝点击