python之excel表操作

python之excel表操作

python对excel表操作主要用到三个库,xlrd,xlwt,xlutils,分别用于excel表读,写,修改操作,以下将一个简单介绍

一、生成excel表:xlwt类

新建excel表,并写入数据

操作下:

 1 import xlwt
 2 #生成excel表,选择编码
 3 book=xlwt.Workbook(encoding='utf-8')
 4 #生成标签页
 5 sheet=book.add_sheet('sheet1',cell_overwrite_ok=True)
 6 #写入数据,参数为 行,列,写入内容
 7 sheet.write(0,0,'序号')
 8 sheet.write(0,1,'明细')
 9 sheet.write(1,0,1)
10 sheet.write(1,1,'python')
11 #保存excel表,路劲注意存在
12 book.save(r'C:UsersMr.WhiteDesktop	est001	est001.xls')

预览一下结果

python之excel表操作

二、读取excel表的内容:xlrd类

 1 #打开excel表
 2 workbook=xlrd.open_workbook(r"C:UsersMr.WhiteDesktoppython	est001excel-write001.xls")
 3 # 获取所有工作区
 4 sheetcount=len(workbook.sheets())
 5 print(u"工作区总数: %s" % sheetcount)
 6 # 获取所有sheet
 7 print(u"工作区的名称:", workbook.sheet_names())
 8 #获取第一个工作区的行数和列数
 9 sheet1 = workbook.sheet_by_index(0)  # sheet索引从0开始
10 sheet1 = workbook.sheet_by_name('sheet1')
11 rows_num = sheet1.nrows
12 cols_num = sheet1.ncols
13 print(u'第一个工作区的行数为%s,列数为%s'%(rows_num,cols_num))
14 # 获取整行和整列的值(数组)
15 rows = sheet1.row_values(3)  # 获取第四行内容
16 cols = sheet1.col_values(2)  # 获取第三列内容
17 print("第4行内容:", rows)
18 print("第3列内容:", cols)
19 print("第2行第1列:", sheet1.cell(1,0).value)
20 print("第2行第4列:", sheet1.cell_value(1,3))
21 print("第3行第4列:", sheet1.row(2)[3].value)
22 print("第4行第4列:", sheet1.cell_value(3, 3))
23 # 获取数据类型
24 print("第2行第1列的数据类型:", sheet1.cell(1, 0).ctype)

三、编辑excel中内容:xlutils.copy

编辑excel表中内容时,会结合使用到xlrd来读取excel表,生成一份副本

 1 #打开一个excel
 2 rb=xlrd.open_workbook(r"C:UsersMr.WhiteDesktoppython	est001excel-write001.xls")
 3 #copy此excel表
 4 wb=xlutils.copy.copy(rb)
 5 #获取sheet对象,通过sheet_by_index()获取的sheet对象没有write()方法
 6 ws=wb.get_sheet(0)
 7 #写入数据
 8 ws.write(1,4,'test001')
 9 ws.write(2,4,'test002')
10 #添加sheet页
11 wb.add_sheet('sheetnn2',cell_overwrite_ok=True)
12 wb.save(r"C:UsersMr.WhiteDesktoppython	est001excel-write001.xls")
编辑excel中内容