python读写Excel表格的实例代码简单实用

这篇文章主要介绍了python读写Excel表格的方法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

安装两个库:pip install xlrd、pip install xlwt

1.python读excel――xlrd

2.python写excel――xlwt

1.读excel数据,包括日期等数据

#coding=utf-8 import xlrd import datetime from datetime import date def read_excel(): #打开文件 wb = xlrd.open_workbook(r'test.xlsx') #获取所有sheet的名字 print(wb.sheet_names()) #获取第二个sheet的表明 sheet2 = wb.sheet_names()[1] #sheet1索引从0开始,得到sheet1表的句柄 sheet1 = wb.sheet_by_index(0) rowNum = sheet1.nrows colNum = sheet1.ncols #s = sheet1.cell(1,0).value.encode('utf-8') s = sheet1.cell(1,0).value #获取一个位置的数据 # 1 ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error print(sheet1.cell(1,2).ctype) print(s) #print(s.decode('utf-8')) #获取整行和整列的数据 #第二行数据 row2 = sheet1.row_values(1) #第二列数据 cols2 = sheet1.col_values(2) #python读取excel中单元格内容为日期的方式 #返回类型有5种 for i in range(rowNum): if sheet1.cell(i,2).ctype == 3: d = xlrd.xldate_as_tuple(sheet1.cell_value(i,2),wb.datemode) print(date(*d[:3]),end='') print('n') if __name__ == '__main__': read_excel()~

运行效果

2.往excel写入数据

#coding=utf-8 import xlwt #设置表格样式 def set_stlye(name,height,bold=False): #初始化样式 style = xlwt.XFStyle() #创建字体 font = xlwt.Font() font.bold = bold font.colour_index = 4 font.height = height font.name =name style.font = font return style #写入数据 def write_excel(): f = xlwt.Workbook() #创建sheet1 sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True) row0 = [u'业务',u'状态',u'北京',u'上海',u'广州',u'深圳',u'状态小计',u'合计'] column0 = [u'机票',u'船票',u'火车票',u'汽车票',u'其他'] status = [u'预定',u'出票',u'退票',u'业务小计'] for i in range(0,len(row0)): sheet1.write(0,i,row0[i],set_stlye("Time New Roman",220,True)) i,j = 1,0 while i

在data.xls种生成了sheet1和sheet2:

总结

以上所述是小编给大家介绍的python读写Excel表格的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程之家网站的支持

如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...