python–xlrd, xlwt, xlutils用法
- xlrd只能读取表格,不能直接修改原表格,复制原表格之后可以修改。支持xlsx, xls文件格式
- xlwt只能修改表格,不能读取表格,支持xlsx, xls文件格式
- xlutils可以将xlrd.Book转为xlwt.Workbook,从而可以读也可以写
xlrd
import xlrd
excel = xlrd.open_workbook('E:/test.xlsx')
返回值为xlrd.book.Book对象,不可修改
获取sheet
table_list = excel.sheet_names() # 获取所有sheet名称,以list方式显示
table = excel.sheets[i]
table = excel.sheet_by_index(i)
table = excel.sheet_by_name('sheet1')
获取行数和列数
rows = table.nrows
cols = table.ncols
获取单元格
cell = table.cell(row,col).value
cell_A1 = table.row(0)[0].value
cell_A2 = table.row(1)[0].value
第一行第一列从0开始,记得加上 .value
获取每行每列
row_values = table.row_values(i)
col_values = table.col_values(i)
xlwt
官网的例子
import xlwt
from datetime import datetime
style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',
num_format_str='#,##0.00')
style1 = xlwt.easyxf(num_format_str='D-MMM-YY')
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
ws.write(0, 0, 1234.56, style0)
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))
wb.save('example.xls')
运行结果:
xlutils
从xlrd读取一个工作簿开始
from os.path import join
from xlrd import open_workbook
rb = open_workbook(join(test_files,'testall.xls'), formatting_info=True, on_demand=True)
接下来使用xlutils.copy复制xlrd.Book对象,再将其转变成可写的xlwt.Workbook对象
from xlutils.copy import copy
wb = copy(rb)
可以在wb中进行修改,并保存
wb.get_sheet(0).write(0,0,'changed!')
wb.save(join(temp_dir.path,'output.xls'))
temp_dir.listdir()