Python 操作 Excel 之 xlwt 库

一、学习概览

大家伙,我是 Gorit,今天我来给大家分享 Python 使用技巧系列之,Python 操作 Excel 表格,对,你没听错,使用 Python 操作 Excel

二、主要内容

  1. 安装 Python 操作 Excel 库之 xlwt
  2. 使用 Python 往 Excel 中写入数据
  3. 小案例:

2.1 安装 xlwt 库

Python 的 xlwt 库是一个优秀的对 Excel 进行读操作的库,因为是第三方包,我们使用传统的 pip install xlwt 可能会出现安装不上的情况,所以我给大家提供了一种便捷的下载方式

  1. pip install -i https://pypi.tuna.tsinghua.edu.cn/simple xlwt

参数解释:-i 使用指定的 pip 源进行下载,我使用的源是 清华大学的源

2.3 小案例

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 --
  3. #@File: task.py
  4. #@author: Gorit
  5. #@contact: gorit@qq.com
  6. #@time: 2020/5/12 23:47
  7. # 操作 Excel 表格
  8. import xlwt
  9. # 获取一个操作表对象
  10. wb = xlwt.Workbook()
  11. # 获取一个工作簿操作对象,及 Sheet1
  12. sheet = wb.add_sheet("scores")
  13. content = ['编号','学生姓名','语文','数学','英语'] # 第一行数据
  14. body = [
  15. {"id":1,"name":"张三","chinese":90,"math":85,"english":77},
  16. {"id":2,"name":"李四","chinese":88,"math":93,"english":80},
  17. {"id":3,"name":"王五","chinese":60,"math":100,"english":99},
  18. {"id":4,"name":"溜溜","chinese":75,"math":80,"english":60}
  19. ]
  20. # 一次性 写入内容(行表,列表,内容),写过了就不能再写入了
  21. for i in range(0,5): # 循环行 0~4
  22. for j in range(0,5): # 循环列 0~4
  23. if i == 0:# 写入第一行数据
  24. sheet.write(i, j, content[j])
  25. else:
  26. if j==0: # 指定往 第一列写入数据
  27. sheet.write(i, j, body[i-1].get("id"))
  28. elif j==1: # 指定往第二列写入数据
  29. sheet.write(i, j, body[i-1].get("name"))
  30. elif j==2:
  31. sheet.write(i, j, body[i-1].get("chinese"))
  32. elif j==3:
  33. sheet.write(i, j, body[i-1].get("math"))
  34. elif j==4:
  35. sheet.write(i, j, body[i-1].get("english"))
  36. # 保存您当前工作表
  37. wb.save("scores.xls")

效果图
image.png

三、课后练习

四、视频操作

五、往期知识分享

1.2