Python课堂13--Excel表格-xlwt模块用法

xlwt只能读不能写
1.导入xlwt模块

import xlwt

2.创建一个二维列表,对表格中的数据进行写入。

stus = [['姓名', '年龄', '性别', '分数'],
         ['mary', 20, '女', 89.9],
         ['mary', 20, '女', 89.9],
         ['mary', 20, '女', 89.9],
         ['mary', 20, '女', 89.9]
         ]

3.新建一个excel表格

book = xlwt.Workbook()

4.添加一个sheet1页

sheet = book.add_sheet('sheet1')

5.用特殊的循环,循环列表,依次将数值插入。
例:stu第一次循环走的是:[‘姓名’, ‘年龄’, ‘性别’, ‘分数’]

row = 0#控制行
for stu in stus:
     col = 0#控制列
     for s in stu:#再循环里面每一列的list值,
         sheet.write(row,col,s)
         col+=1
     row+=1

6.默认保存到当前目录下(该项目目录名称下),也可以将括号中的路径进行修改,保存到指定位置。

book.save('stu_1.xls')

整理代码

import xlwt
stus = [['姓名', '年龄', '性别', '分数'],
         ['mary', 20, '女', 89.9],
         ['mary', 20, '女', 89.9],
         ['mary', 20, '女', 89.9],
         ['mary', 20, '女', 89.9]
         ]
book = xlwt.Workbook()
sheet = book.add_sheet('case1_sheet')
row = 0
for stu in stus:
     col = 0
     for s in stu:
         sheet.write(row,col,s)
         col+=1
     row+=1
book.save('stu_1.xls')

例:
在E盘创建一个名为example的表格,在表格中的“practice”页中的第三行第三列位置输入“nihao”。

import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet("practice")
sheet.write(2,2,"nihao")
book.save("e://example.xls")

猜你喜欢

转载自blog.csdn.net/weixin_44362227/article/details/86565399