特色简介
xlrd主要用来读excel,针对.xls格式;
xlwt主要用来写excel,针对.xls格式,超出excel 的单格内容长度上限32767,就会报错;
xlutils结合xlrd可以达到修改excel文件目的,需要注意的是你必须同时安装这三个库;
openpyxl读写.xlsx格式的excel,无长度限制;
xlsxwriter可以写excel文件并加上图表,缺点是不能打开/修改已有文件,意味着使用 xlsxwriter 需要从零开始。
xlrd
import xlrd
#打开excel
data = xlrd.open_workbook('demo.xls') #注意这里的workbook首字母是小写
#查看文件中包含sheet的名称
data.sheet_names()
#得到第一个工作表,或者通过索引顺序 或 工作表名称
table = data.sheets()[0]
table = data.sheet_by_index(0)
table = data.sheet_by_name(u'Sheet1')
#获取行数和列数
nrows = table.nrows
ncols = table.ncols
#获取整行和整列的值(数组)
table.row_values(i)
table.col_values(i)
#循环行,得到索引的列表
for rownum in range(table.nrows):
print table.row_values(rownum)
#单元格
cell_A1 = table.cell(0,0).value
cell_C4 = table.cell(2,3).value
#分别使用行列索引
cell_A1 = table.row(0)[0].value
cell_A2 = table.col(1)[0].value
xlwt
import xlwt #新建一个excel文件
file = xlwt.Workbook() #注意这里的Workbook首字母是大写 #新建一个sheet
table = file.add_sheet('sheet name') #写入数据table.write(行,列,value)
table.write(0,0,'test')
‘‘‘
如果对一个单元格重复操作,会引发
returns error:
Exception: Attempt to overwrite cell:
sheetname=u'sheet 1' rowx=0 colx=0
所以在打开时加cell_overwrite_ok=True解决
’’’
table = file.add_sheet('sheet name',cell_overwrite_ok=True) #保存文件
file.save('demo.xls')
#另外,使用style
style = xlwt.XFStyle() #初始化样式 font = xlwt.Font() #为样式创建字体
font.name = 'Times New Roman'
font.bold = True
style.font = font #为样式设置字体
table.write(0, 0, 'some bold Times text', style) # 使用样式
openpyxl
from openpyxl import Workbook
wb = Workbook() #取得当前有效的work sheet
ws = wb.active #直接根据位置进行赋值
ws['A1'] = 42 #也可以直接添加一行
ws.append([1, 2, 3]) #可以直接存储Python的时间类型变量
import datetime
ws['A2'] = datetime.datetime.now() #保存文件
wb.save("sample.xlsx")
https://www.missshi.cn/api/view/blog/5a001868e519f50d04000350
http://blog.51cto.com/daimalaobing/2089686
实例一
from openpyxl import load_workbook
class OperationExcel:
def __init__(self, file_name=None, sheet_id=None):
if file_name:
self.file_name = file_name
self.sheet_id = sheet_id
else:
self.xls = '../case/case.xlsx'
self.file_name = self.xls
self.sheet_id = 0
self.data = self.get_data() #获取sheets的内容
def get_data(self):
data = load_workbook(self.file_name)
sheetnames = data.get_sheet_names() #获取表单名字
tables = data.get_sheet_by_name(sheetnames[self.sheet_id]) #打开下标为x的表单
return tables #获取单元格的行数
def get_lines(self):
tables = self.data
return tables.max_row #获取某一个单元格的内容
def get_cell_value(self, row, col):
return self.data.cell(row=row, column=col).value #写入数据
def write_value(self, row, col, value):
data = load_workbook(self.file_name)
sheetnames = data.get_sheet_names() #获取表单名字
tables = data.get_sheet_by_name(sheetnames[self.sheet_id]) #打开下标为0的表单
tables.cell(row=row, column=col,value=value)
data.save(self.file_name) #根据对应的caseid 找到对应行的内容
def get_rows_data(self, case_id):
row_num = self.get_row_num(case_id)
rows_data = self.get_row_values(row_num)
return rows_data #根据对应的caseid找到对应的行号
def get_row_num(self, case_id):
num = 1
clols_data = self.get_cols_data()
for col_data in clols_data:
if case_id in col_data:
return num
num = num+1 #根据行号,找到该行的内容
def get_row_values(self, row):
tables = self.data
row_data = []
for cell in list(tables.rows)[row]:
row_data.append(cell.value)
return row_data #获取某一列的内容
def get_cols_data(self, col_id=None):
tables = self.data
col_data = []
if col_id != None:
for cell in list(tables.columns)[col_id]:
col_data.append(cell.value)
else:
for cell in list(tables.columns)[0]:
col_data.append(cell.value)
return col_data if __name__ == '__main__':
opers = OperationExcel()
opers.write_value(1, 3, 'nihaolllllll')
print(opers.get_cell_value(2,4))#单元格从1开始,非从0开始
print(opers.get_cols_data(1))
print(opers.get_row_values(1))
print(opers.get_data())
print(opers.get_lines())
print(opers.get_rows_data(''))
实例二
import xlrd,xlwt
import openpyxl def write03(path):
wb = xlwt.Workbook()
sheet = wb.add_sheet("2003测试表")
value = [["名称", "价格", "出版社", "语言"],
["如何高效读懂一本书", "22.3", "机械工业出版社", "中文"],
["暗时间", "32.4", "人民邮电出版社", "中文"],
["拆掉思维里的墙", "26.7", "机械工业出版社", "中文"]]
for i in range(0,4):
for j in range(0,len(value[i])):
sheet.write(i,j,value[i][j])
wb.save(path)
print("2003写入数据成功!") def read03(path):
workbook = xlrd.open_workbook(path)
sheets = workbook.sheet_names()
worksheet = workbook.sheet_by_name(sheets[0])
for i in range(0, worksheet.nrows):
row = worksheet.row(i)
for j in range(0, worksheet.ncols):
print(worksheet.cell_value(i,j),"\t",end="")
print() def write07(path):
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = '2007测试表'
value = [["名称", "价格", "出版社", "语言"],
["如何高效读懂一本书", "22.3", "机械工业出版社", "中文"],
["暗时间", "32.4", "人民邮电出版社", "中文"],
["拆掉思维里的墙", "26.7", "机械工业出版社", "中文"]]
for i in range(0,4):
for j in range(0,len(value[i])):
sheet.cell(row=i+1, column=j+1, value=str(value[i][j]))
wb.save(path)
print("2007写入数据成功!") def read07(path):
wb = openpyxl.load_workbook(path)
sheet = wb.get_sheet_by_name('2007测试表')
for row in sheet.rows:
for cell in row:
print(cell.value,"\t",end="")
print() file_2003 = '../data/2003.xls'
file_2007 = '../data/2007.xlsx' write03(file_2003)
read03(file_2003)
write07(file_2007)
read07(file_2007)