zoukankan      html  css  js  c++  java
  • python操作excel之 模块 xlrd

    xlrd是专门用来在python中读取微软execel的模块,可以自己直接下载安装,也可以通过包管理器安装。

    官方资料:

    下载地址:http://pypi.python.org/pypi/xlrd

    官网地址:http://www.python-excel.org/

    文档地址:https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html

    文档pdf下载:http://www.simplistix.co.uk/presentations/python-excel.pdf

    基本操作:

    [python] view plain copy
     
    1. # encoding : utf-8       #设置编码方式  
    2.   
    3. import xlrd                    #导入xlrd模块  
    4.   
    5. #打开指定文件路径的excel文件  
    6.   
    7. xlsfile = r'D:AutoPlanapisnew.xls'   
    8. book = xlrd.open_workbook(xlsfile)     #获得excel的book对象  
    9.   
    10. #获取sheet对象,方法有2种:  
    11. sheet_name=book.sheet_names()[0]          #获得指定索引的sheet名字  
    12. print sheet_name  
    13. sheet1=book.sheet_by_name(sheet_name)  #通过sheet名字来获取,当然如果你知道sheet名字了可以直接指定  
    14. sheet0=book.sheet_by_index(0)     #通过sheet索引获得sheet对象  
    15.   
    16. #获取行数和列数:  
    17.   
    18. nrows = sheet.nrows    #行总数  
    19. ncols = sheet.ncols   #列总数  
    20.   
    21. #获得指定行、列的值,返回对象为一个值列表  
    22.   
    23. row_data = sheet.row_values(0)   #获得第1行的数据列表  
    24. col_data = sheet.col_values(0)  #获得第一列的数据列表,然后就可以迭代里面的数据了  
    25.   
    26. #通过cell的位置坐标获得指定cell的值  
    27. cell_value1 = sheet.cell_value(0,1)  ##只有cell的值内容,如:http://xxx.xxx.xxx.xxx:8850/2/photos/square/  
    28. print cell_value1  
    29. cell_value2 = sheet.cell(0,1) ##除了cell值内容外还有附加属性,如:text:u'http://xxx.xxx.xxx.xxx:8850/2/photos/square/'  
    30. print cell_value2  


    是不是很方便啊,恩,比用vbs调用的excel COM对象简便多了。而且这个支持linux平台。

    =====================================xls的写方法使用xlwt模块===================================================

    [python] view plain copy
     
      1. #encoding:utf-8       #设置编码方式    
      2.     
      3. import xlwt  
      4. wbk = xlwt.Workbook(encoding='utf-8', style_compression=0)  
      5. sheet = wbk.add_sheet('sheet 1', cell_overwrite_ok=True)  ##第二参数用于确认同一个cell单元是否可以重设值。  
      6.   
      7. sheet.write(0,0,'some text')  
      8. sheet.write(0,0,'this should overwrite')   ##重新设置,需要cell_overwrite_ok=True  
      9.   
      10. style = xlwt.XFStyle()  
      11. font = xlwt.Font()  
      12. font.name = 'Times New Roman'  
      13. font.bold = True  
      14. style.font = font  
      15. sheet.write(0, 1, 'some bold Times text', style)  
      16.   
      17. wbk.save('D:TestData2.xls')    ##该文件名必须存在  
  • 相关阅读:
    python二进制转换
    git的使用
    c++primer plus笔记
    c++primer 学习笔记
    二分查找
    字符串全排列
    斐波那契数列
    JavaScript 相关
    HTTP记录
    前端笔记
  • 原文地址:https://www.cnblogs.com/zknublx/p/5940943.html
Copyright © 2011-2022 走看看