Python读写excel文件
来源:互联网 发布:乐视淘宝旗舰店 编辑:程序博客网 时间:2024/05/19 13:45
Python读写需要使用的库为xlrd和xlwt
一个最简单的例子来说明这两个库的基本用法:
import xlwtimport xlrdwb = xlwt.Workbook()ws = wb.add_sheet('mysheet')ws.write(0, 0, 1.01) #把表格想象成二维表,前2各参数是行列ws.write(0, 1, 'haha')ws.write(1,0,'A')ws.write(1,1,'B')ws.write(1,2,'SUM')ws.write(2, 0, 123)ws.write(2, 1, 456)ws.write(2,2,110)ws.write(2, 3, xlwt.Formula("A3+B3"))wb.save('example.xls')wb = xlrd.open_workbook('example.xls')sn = wb.sheet_names() #获得工作所有表名print('sheet names :'+str(sn))#wb.sheet_by_name('name') 通过工作表名进入工作表sh = wb.sheet_by_index(0) #通过index进入工作表sheets = wb.sheets() #获取所有工作表for sheet in sheets: for row in range(sheet.nrows): for col in range(sheet.ncols): print(sheet.cell(row,col).value)更详细的用法:
xlwt
http://pypi.Python.org/pypi/xlrd
导入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) # 使用样式
xlwt 允许单元格或者整行地设置格式。还可以添加链接以及公式。可以阅读源代码,那里有例子:
dates.py, 展示如何设置不同的数据格式
hyperlinks.py, 展示如何创建超链接 (hint: you need to use a formula)
merged.py, 展示如何合并格子
row_styles.py, 展示如何应用Style到整行格子中.
具体的例子可以看:
http://scienceoss.com/write-excel-files-with-python-using-xlwt/
- python读写Excel文件
- python读写excel文件
- Python读写excel文件
- Python 读写Excel文件
- python读写excel文件
- Python读写excel文件
- python读写Excel文件
- Python读写excel文件
- python读写excel文件
- python读写excel文件
- python读写excel文件
- python 操作excel 读写文件
- 用Python读写Excel文件
- 用Python读写Excel文件
- 用Python读写Excel文件
- 用Python读写Excel文件
- python-23-读写excel文件
- python之读写excel文件
- Two Sum
- 2017.2.25 1. Two Sum [easy]
- aria2参数说明 bittorrent标签
- c++中new/delete重载总结
- 修改Toolbar返回按钮的颜色
- Python读写excel文件
- WinEdt 7.0 快捷键
- 分隔符,解析字符串
- codeforces 777E Hanoi Factory (栈+贪心)
- Oracle 中,获取指定用户所有有权限访问的表的基本信息、分页实现
- 关于Java中Stack类的使用
- 时间同步
- Android移动应用基础学习交流-初学体会
- BZOJ 3162 独钓寒江雪