Python操作Excel,主要用到xlrd和xlwt这两个库,即xlrd是读Excel,xlwt是写Excel的库
1、Python读取Excel表格 ,使用xlrd库
整体思路为,打开文件,选定表格,读取行列内容,读取表格内数据
1 import xlrd 2 import os 3 path = os.path.join(os.path.dirname(__file__),'data.xls') 4 print(path) 5 6 def readExcel(): 7 excel = xlrd.open_workbook(path) 8 excel.sheet_names() #获取所有的表格名称 9 sheet1 = excel.sheet_by_index(0) #通过索引获取表格 10 sheet2 = excel.sheet_by_name("测试") #通过名字获取表格 11 row = sheet1.row_values(1) #获取某行的内容,列表形式返回 12 col = sheet1.col_values(0) #获取某列的内容,列表形式返回 13 data1 = sheet1.cell(1,3).value #方法1,获取表格里的具体内容 14 data2 = sheet1.cell_value(2,3) #方法2,获取表格里的具体内容 15 data3 = sheet1.row(3)[3].value #方法3,获取表格里的具体内容 16 print(row) 17 print(col) 18 print(data1) 19 print(data2) 20 print(data3) 21 22 if __name__ == '__main__': 23 readExcel()
当单元格的数据为日期格式时,普通获取后显示的是浮点数
Python读取Excel中单元格的内容返回的有5种类型,即上面例子中的ctype:
ctype : 0 empty,1 string,2 number, 3 date,4 boolean,5 error
即date的ctype=3,这时需要使用xlrd的xldate_as_tuple来处理为date格式
1 import xlrd 2 import os 3 from datetime import date,datetime 4 path = os.path.join(os.path.dirname(__file__),'data.xls') 5 print(path) 6 7 def readExcel(): 8 excel = xlrd.open_workbook(path) 9 sheet1 = excel.sheet_by_index(0) #通过索引获取表格 10 if sheet1.cell(1,4).ctype ==3: #获取单元格的ctype是否为3 11 value = xlrd.xldate_as_tuple(sheet1.cell_value(1,4),excel.datemode) 12 print(value) 13 print(date(*value[:3])) 14 print(date(*value[:3]).strftime('%Y/%m/%d')) 15 else: 16 value = sheet1.cell_value(1,4) 17 print(value) 18 19 if __name__ == '__main__': 20 readExcel()
2、Python写入Excel表格,使用xlwt库,xlwt库是一种”无则创建,有则建新”的覆盖写入方式,也就是只能是新建
1 import xlwt 2 3 #设置表格样式 4 def set_style(name,height,bold=False): 5 style = xlwt.XFStyle() 6 font = xlwt.Font() 7 font.name = name 8 font.bold = bold 9 font.color_index = 4 10 font.height = height 11 style.font = font 12 return style 13 14 #写Excel 15 def write_excel(): 16 f = xlwt.Workbook() 17 sheet1 = f.add_sheet('学生',cell_overwrite_ok=True) 18 row0 = ["姓名","年龄","出生日期","爱好"] 19 colum0 = ["张三","李四","恋习Python","小明","小红","无名"] 20 #写第一行 21 for i in range(0,len(row0)): 22 sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True)) 23 #写第一列 24 for i in range(0,len(colum0)): 25 sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True)) 26 27 sheet1.write(1,2,'2006/12/12') 28 # sheet1.write_merge(6,6,1,3,'未知')#合并行单元格 29 # sheet1.write_merge(1,2,3,3,'打游戏')#合并列单元格 30 # sheet1.write_merge(4,5,3,3,'打篮球') 31 32 f.save('test.xls') 33 34 if __name__ == '__main__': 35 write_excel()
3、Python实现向Excel表格中填写内容,那么就要用到xlutils库,首先以“只读”方式用xlrd打开页面,再用xlutils.copy复制,再调用.write方法写入内容。
1 import xlrd 2 import os 3 from xlutils.copy import copy 4 path = os.path.join(os.path.dirname(__file__),'data.xls') 5 print(path) 6 7 def addExcel(): 8 excel = xlrd.open_workbook(path,formatting_info=True) #formatting_info=True保留原有的数据格式 9 new_excel = copy(excel) 10 sheet = new_excel.get_sheet(0) # 通过索引获取表格 11 sheet.write(3,4,'2019-8-28') 12 new_excel.save(path) 13 14 if __name__ == '__main__': 15 addExcel()