一:需要用到的库
- 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") # 覆盖原来的文件