zoukankan      html  css  js  c++  java
  • python学习笔记(十八)python操作excel

    python操作excel需要安装通过pip安装xlwt, xlrd这两个模块:

      pip install xlwt

      pip insall xlrd

    操作excel ,写入excel:

     1 import xlwt
     2 book=xlwt.Workbook()#新建一个excel
     3 sheet=book.add_sheet('sheet1')##添加一个sheet页
     4 sheet.write(0,0,'姓名')
     5 sheet.write(0,1,'性别')
     6 sheet.write(0,2,'年龄')
     7 book.save('stu.xls')##不能用xlsx结尾,微软的不能用xlsx结尾office,wps的随便
     8 
     9 title = ['姓名','年龄','性别','分数']
    10 stus = [['mary', 20, '', 89.9],
    11         ['mary', 20, '', 89.9],
    12         ['mary', 20, '', 89.9],
    13         ['mary', 20, '', 89.9]]
    14 
    15 cols=0
    16 for t in title:
    17     sheet.write(0,cols,t)
    18     cols+=1
    19 row=1
    20 for stu in stus:
    21     new_cols=0:
    22     for s in stu:
    23         sheet.write(row,new_cols,s)
    24         new_cols+=1
    25     row+=1
    26 book.save('stu.xls')

     读取excel:

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

    修改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)
    7 sheet.write(1,0,'xiaohei')
    8 book2.save('stu.xls')#可以写不同的名字,直接生成一个excel;如果写相同的名字,则直接修改,覆盖之前的内容。
  • 相关阅读:
    idea设置全局ignore
    win 2012 安装mysql 5.7.20 及报错 This application requires Visual Studio 2013 Redistributable. Please ins
    win 2012 安装mysql 5.7.20 及报错 This application requires Visual Studio 2013 Redistr
    kafka 删除 topic
    java编译中出现了Exception in thread “main" java.lang.UnsupportedClassVersionError
    Centos中使用yum安装java时,没有jps的问题的解决
    Spring 整合Junit
    Spring纯注解配置
    Spring 基于注解的 IOC 配置
    打印java系统的信息
  • 原文地址:https://www.cnblogs.com/wxcx/p/8384879.html
Copyright © 2011-2022 走看看