使用Python读取,写入,追加excel文件

一:需要用到的库

  • xlrd:读取excel文件
  • xlrd:写入excel文件
  • xlutils:修改/追加excel文件

直接pip install 库名即可安装成功

二:官方文档

如果想详细了解,请一定阅读官方文档

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

三:xlrd读取excel文件

该demo读取出所有单元格

from xlrd import open_workbook, cellname
 book = open_workbook('odd.xls') # 打开excel文件
 sheet = book.sheet_by_index(0) # 选取第一张表
 print(sheet.name)
 print(sheet.nrows)
 print(sheet.ncols)
 for row_index in range(sheet.nrows):
     for col_index in range(sheet.ncols):
         print(cellname(row_index, col_index), end='-') # 输出单元格坐标
         print(sheet.cell(row_index, col_index).value) # 输出单元格的值

四:xlwd写入excel文件

这个库只能新建一个excel文件,将数据写入其中,如果想要在已有的excel里修改,需要用到xlutils库

xlwt创建一个Workbook对象,使用它,最后调用sava方法即可
sava方法中传入写入的路径的字符串或文件

如果你读取的数据很大,row超过上千行,建议在每1000行的时候,使用flush_row_data()方法,这样会降低内存占用

from tempfile import TemporaryFile
from xlwt import Workbook


book = Workbook() # 创建Workbook对象
sheet1 = book.add_sheet('Sheet 1') # 添加一张工作表
sheet1.write(0,0,'A1') 
sheet1.write(0,1,'B1') # 在第0行,第1列,写入数据B1
row1 = sheet1.row(1) # 第一行
row1.write(0,'A2') 
row1.write(1,'B2') # 第1行,第1列,写入数据B2
sheet1.col(0).width = 10000 # 设置第0列的宽度

book.save('simple.xls') # 保存

五、追加excel文件

from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("simple2.xls")  # 打开需要追加的文件
row = rb.sheet_by_index(0).nrows # 得到当前excel文件行数
wb = copy(rb)  # 将rb从xlrd对象转变为xlwt对象
ws = wb.get_sheet(0)  # 得到sheet
ws.write(row, 0, 'value') # 追加到最后一行
wb.save("simple2.xls")  # 覆盖原来的文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值