zoukankan      html  css  js  c++  java
  • Python基础学习七 Excel操作

    python操作excel,python操作excel使用xlrd、xlwt和xlutils模块,

    xlrd模块是读取excel的,xlwt模块是写excel的,xlutils是用来修改excel的。

    例子1:新建Excel,并添加数据

    1 import xlwt
    2 xld = xlwt.Workbook() # 新建一个excel文件
    3 sheet = xld.add_sheet('sheet1') # 添加一个sheet表
    4 sheet.write(0,0,'姓名')#第一行第一列
    5 sheet.write(0,1,'性别')#第一行第二列
    6 sheet.write(0,2,'年龄')#第一行第三列
    7 xld.save('stu.xls')# 读的时候可以是xlsx的格式,但是写的时候不允许
    8 xld.save(r'C:UsersLOUISDesktopstu.xls') # 存指定位置

    例子2:新建Excel,并添加数据

     1 import xlwt
     2 title = [ '姓名','年龄','性别','分数']
     3 
     4 stus = [
     5         ['user1', 18, '', 89.9],
     6         ['user2', 20, '', 90],
     7         ['user3', 19, '', 80],
     8         ['user4', 20, '', 70]
     9         ]
    10 
    11 book = xlwt.Workbook()# 新建一个excel文件
    12 sheet = book.add_sheet('sheet2')# 添加一个sheet表
    13 column = 0 #控制列
    14 for t in title:
    15     sheet.write(0,column,t)
    16     column+=1
    17 row =1 # 控制行
    18 
    19 for stu in stus:
    20     new_col = 0  # 控制列
    21     for s in stu:# 控制写每一列的
    22         sheet.write(row,new_col,s)
    23         new_col+=1
    24     row+=1
    25 book.save('stu.xls')
    26 book.save(r'C:UsersLOUISDesktopstu.xls')

    例子3:读取Excel

     1 import xlrd
     2 book = xlrd.open_workbook('stu.xls') #打开一个excel
     3 sheet = book.sheet_by_index(0) #根据顺序获取sheet
     4 # sheet2 = book.sheet_by_name('sheet1') #根据sheet页名字获取sheet
     5 # print(sheet.cell(0,0).value)  #指定行和列获取数据
     6 # print(sheet.ncols) #获取excel里面有多少列
     7 # print(sheet.nrows) #获取excel里面有多少行
     8 sheet.row_values(1)#取第几行的数据
     9 print(sheet.col_values(1)) #取第几列的数据
    10 for i in range(sheet.nrows): # 0 1 2 3 4 5
    11     print(sheet.row_values(i)) #取第几行的数据

    例子4:修改Excel

    1 from xlutils.copy import copy
    2 import xlrd
    3 book1 = xlrd.open_workbook('stu.xls')
    4 book2 = copy(book1)  #拷贝一份原来的excel
    5 sheet = book2.get_sheet(0) #获取第几个sheet页
    6 sheet.write(1,3,0)# 第一行第三列修改为 0
    7 sheet.write(1,5,'louis') # 第一行第5列修改为louis
    8 book2.save('stu.xls
  • 相关阅读:
    ArcGIS Engine 笔记-控件类型
    个人简历(公开版)
    生活垃圾处理相关
    如何让nextcloud支持avi文件在线播放
    NextCloud前端支持播放mov文件
    使用Huginn抓取Discourse论坛
    使用WordPress制作微信小程序
    Github 快速建库上传本地代码
    BestSync多终端文件资料同步利器
    ABAP-SAP HANA 数据库并发控制
  • 原文地址:https://www.cnblogs.com/louis-w/p/8400173.html
Copyright © 2011-2022 走看看