Python_操作excel

2021/6/1 20:21:03

本文主要是介绍Python_操作excel,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

python中与excel操作相关的模块:

  • xlrd库:从excel中读取数据,支持xls、xlsx
  • xlwt库:对excel进行修改操作,不支持对xlsx格式的修改
  • xlutils库:在xlw和xlrd中,对一个已存在的文件进行修改。
  • openpyxl:主要针对xlsx格式的excel进行读取和编辑。

安装方式:pip install openpyxl

 

import xlwt

book = xlwt.Workbook()
sheet = book.add_sheet("sheet1")
sheet.write(0,0,"id")
sheet.write(1,0,"1")
book.save("test.xls") #结尾用xlsx的话,用office打开有问题,wps打开没问题

title = ["id","name","sex","city"]
students = [
    [1,"xiaohei","男","北京"],
    [2,"xiaolan","男","北京"],
    [3,"candy","女","深圳"],
    [4,"lucy","女","北京"],
]
students.insert(0,title)

 row = 0 #行号
 for student in students: #控制行
     col = 0  # 列号
     for value in student: #控制列
         sheet.write(row,col,value)
         col+=1
     row+=1

for row,student in enumerate(students):
    for col,value in enumerate(student):
        sheet.write(row,col,value)

book.save("test.xls")

 


data = xlrd.open_workbook(table_name)
table = data.sheets()[0]
nrows,ncols = table.nrows,table.ncols
for i in range(1, nrows):
  value1= table.cell(i, 1).value    获取第i行,第1列单元格数据
  print(value1)



这篇关于Python_操作excel的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程