数据导入之前需要安装 xlwt依赖包,安装的方法很简单,直接 pip install xlwt
代码如下:
# -*- coding:UTF-8 -*-
import xlwt
def write_excel():
#创建excel
f = xlwt.Workbook()
#创建sheet
sheet1 = f.add_sheet("学生表",cell_overwrite_ok=True)
row = ["姓名","班级","课程","分数"]
col = ["张三","李四","小明","小花","小红"]
#写入第一行数据
for i in range(0,len(row)):
sheet1.write(0,i,row[i])
#写入第一列数据
for i in range(0,len(col)):
sheet1.write(i+1,0,col[i])
sheet1.write(1,2,"语文")
sheet1.write_merge(5,5,1,2,"94班") #合并行单元格
sheet1.write_merge(2,3,3,3,90) #合并列单元格
sheet1.write_merge(3,4,2,2,"英语") #合并列单元格
f.save("C:\\Users\\admin\Desktop\wb.xls")
if __name__ == "__main__":
write_excel()