1、Excel文件-Sheet1
姓名 |
年龄 |
出生日期 |
关系 |
张三 |
20 |
1998/1/1 |
朋友 |
李四 |
21 |
1997/1/1 |
王五 |
22 |
1996/1/1 |
同学 |
赵六 |
23 |
1995/1/1 |
孙七 |
24 |
1994/1/1 |
周八 |
25 |
暂无 |
2、读取Sheet1普通单元格和日期单元格
# coding:utf-8
import xlrd
from datetime import date
def read_excel():
workbook = xlrd.open_workbook("./demo.xlsx")
print(workbook.sheet_names())
sheet1 = workbook.sheet_by_index(0)
print(sheet1.name, sheet1.nrows, sheet1.ncols)
rows = sheet1.row_values(0)
cols = sheet1.col_values(0)
print(rows, cols)
#普通单元格
print(sheet1.cell(1, 0).value)
#日期单元格
print(sheet1.row(1)[2].value)
print(sheet1.cell(1, 2).ctype) # ctype-0:empty, 1:string, 2:number, 3:date, 4:boolean, 5:error
#方法一
datetime = xlrd.xldate_as_datetime(sheet1.cell(1, 2).value, 0)
print(datetime)
#方法二
date_value = xlrd.xldate_as_tuple(sheet1.cell(1, 2).value, 0)
print(date_value)
date_temp = date(*date_value[:3]).strftime("%Y/%m/%d")
print(date_temp)
if __name__ == "__main__":
read_excel()
3、读取Sheet1合并单元格
# coding:utf-8
import xlrd
def read_excel():
workbook = xlrd.open_workbook("./demo.xlsx")
sheet1 = workbook.sheet_by_index(0)
print(sheet1.merged_cells)
merge = []
for(row, row_range, col, col_range) in sheet1.merged_cells:
merge.append([row, col])
print(merge)
for index in merge:
print(sheet1.cell(index[0], index[1]).value)
if __name__ == "__main__":
read_excel()
4、Excel文件-Sheet2
姓名 |
年龄 |
出生日期 |
关系 |
张三 |
父亲 |
|
|
母亲 |
|
儿子 |
|
女儿 |
|
李四 |
父亲 |
|
|
母亲 |
|
儿子 |
|
女儿 |
|
王五 |
父亲 |
|
|
母亲 |
|
儿子 |
|
女儿 |
|
赵六 |
父亲 |
|
|
母亲 |
|
儿子 |
|
女儿 |
|
孙七 |
父亲 |
|
|
母亲 |
|
儿子 |
|
女儿 |
|
周八 |
父亲 |
|
|
母亲 |
|
儿子 |
|
女儿 |
|
合计 |
|
|
5、创建Sheet2并写入相应数据及格式
# coding:utf-8
import xlwt
def set_style(name, height, bold=False):
style = xlwt.XFStyle() #初始化样式
font = xlwt.Font()
font.name = name
font.bold = bold
font.colour_index = 0xFFFF
font.height = height
style.font = font
return style
def write_excel():
workbook = xlwt.Workbook()
sheet1 = workbook.add_sheet("sheet2", cell_overwrite_ok=True)
row0 = [u"姓名", u"年龄", u"出生日期", u"关系"]
col0 = [u"张三", u"李四", u"王五", u"赵六", u"孙七", u"周八"]
status = [u"父亲", u"母亲", u"儿子", u"女儿"]
#生成第一行
for i in range(0, len(row0)):
sheet1.write(0, i, row0[i], set_style("Times New Roman", 200, True))
#生成第一列和最后一列
j = 1
k = 0
while j < 4*len(col0) and k < len(col0):
sheet1.write_merge(j, j + 3 , 0, 0, col0[k], set_style("Times New Roman", 200, True))
sheet1.write_merge(j, j + 3, 3, 3)
j = j + 4
k = k + 1
sheet1.write_merge(25, 25 , 0, 1, u"合计", set_style("Times New Roman", 200, True))
#生成第二列
p = 0
while p < 4*len(col0):
for q in range(0, len(status)):
sheet1.write(p+q+1, 1, status[q])
p = p + 4
workbook.save("demo.xls")
if __name__ == "__main__":
write_excel()