Python Execl模块

Python 使用 xlrdxlwt 两个模块来操作 Execl表格,分别用来读和写

xlrd 读取表格

# 打开execl文件
workbook = xlrd.open_workbook(r'E:\deploy_log.xlsx')
# 输出所有sheet,输出为列表
print workbook.sheet_names()    
# 获取 工作表(sheet)名称
sheet1_name = workbook.sheet_names()[0]
# 通过索引获取sheet
sheet1 = workbook.sheet_by_index(0)
# 通过名称获取sheet
sheet1 = workbook.sheet_by_name('first_sheet')
print "sheet表名:%s, 行数:%d, 列数:%d" % (sheet1_name, sheet1.nrows, sheet1.ncols)

# 获取指定行或指定列的内容
rows = sheet1.row_values(3)
cols = sheet1.col_values(4)
print '第3行', rows
print '第4列', cols

# 获取单元格内容
print '单元格内容', sheet1.cell(3,0).value
print '单元格内容', sheet1.cell_value(3,0)
print '单元格内容', sheet1.row(3)[4].value

# 获取单元格内容的数据类型
# ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
print sheet1.cell(3, 0).ctype
print sheet1.cell(3, 4).ctype

# 之前时间输出为42851.6937037,下边进行时间转换
print "获取时间: ", xlrd.xldate_as_tuple(sheet1.cell_value(3,4), workbook.datemode) 

# 获取合并的单元格
workbook_format = xlrd.open_workbook(r'E:\deploy_log.xlsx', formatting_info=True)
sheet1_format = workbook_format.sheet_by_index(0)
print sheet1.merged_cells

xlwt 写表格

官方参照:
https://pypi.python.org/pypi/...
http://xlwt.readthedocs.io/en...

# 创建表格对象
f = xlwt.Workbook()
sheet_new = f.add_sheet(u'first_sheet', cell_overwrite_ok=True)

# 设置表格style
style = xlwt.XFStyle()
font = xlwt.Font()
font.name = 'Times New Roman'
font.bold = bold
font.color_index = 4
font.height = 220
style.font = True

# 写数据
sheet_new.write(0, 0, 'host', style)
sheet_new.write(0, 1, 'warname', style)
sheet_new.write(0, 2, 'runtime', style)

Satezheng
7 声望0 粉丝