欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

详解python操作生成excel表格,并且填充数据

程序员文章站 2024-03-23 13:07:22
...

最近在研究python操作excel表格的问题,首先读取excel表格觉得平时用的多,不怎么有难度,就是pyhon生成excel表格的时候,平时不怎么用,所以重点研究了一下,现总结如下:

1.首先用到的包是 xlwt, 所以导入:import xlwt;

2.定位创建excel表格的方法,如下:

def set_style(name,height,bold=False):
#初始化表格样式;
style=xlwt.XFStyle()
#为样式创建字体
font=xlwt.Font()
# print(font)
font.name=name
font.bold=bold
# font.colour_index=4
font.color_index = 4
font.height=height

style.font =font
return style

3.重点来了,下面的方法为创建工作簿,并且填充数据;
def write_excel():
sheet3=f.add_sheet(u"sheet3",cell_overwrite_ok=True)
row0=[u’id’,u’name’,u’sex’,u’age’,u’class’]
column0=[u’001’,u’002’,u’003’,u’004’,u’005’]
#第二列
column1 = [u’小张’, u’小王’, u’小刘’, u’小周’, u’小何’]
# 第三列
column2 = [u’男’, u’男’, u’男’, u’女’, u’女’]
#生成第一行:
for i in range(0,len(row0)):
sheet3.write(0,i,row0[i],set_style(‘Times New Roman’,220,True))
#生成第一列:
for i in range(0,len(column0)):
sheet3.write(i+1,0,column0[i],set_style(‘Times New Roman’,220,True))
# 生成第一行:
# for i in range(0, len(row0)):
# sheet3.write(0, i, row0[i], set_style(‘Times New Roman’, 220, True))
# #生成第二列:
for i in range(0,len(column1)):
# print(“666”)
# i + 2:第几行 1:第几列
sheet3.write(i+1, 1, column1[i], set_style(‘Times New Roman’, 220, True))
# 生成第三列:
for i in range(0,len(column2)):
sheet3.write(i+1,2,column2[i],set_style(‘Times New Roman’, 220, True))
# 第四列
column3 = [u’11’, u’12’, u’13’, u’14’, u’15’]
for i in range(0,len(column3)):

    sheet3.write(i+1,3,column3[i],set_style('Times New Roman', 220, True))

sheet3.write_merge(1, 3, 4,4,u'一年级'.center(10))
sheet3.write_merge(4, 5, 4, 4, u'三年级'.center(10))

f.save("zcl.xlsx")

效果图如下:
详解python操作生成excel表格,并且填充数据
接下来解释一下:
sheet3.write_merge(1, 3, 4,4,u’一年级’.center(10))
敲黑板:

  1. 其中的1,3表示合并第1到三行(除去表头,表头是第0行);

  2. 其中的4,4表示合并第四列(列数也是从第0列开始的)以此类推;

  3. .center表示这一列的文字居中显示,有许多显示方式,这里我不再一一论述!

相关标签: python mysql