python 操作 EXECL ---xlrd

*********读取

1、常用单元格中的数据类型

    0 empty,1 string(text), 2 number, 3 date, 4 boolean, 5 error, 6 blank

  2、导入模块

      import xlrd

   3、打开Excel文件读取数据

       data = xlrd.open_workbook(filename)

   4、常用的函数

        excel中最重要的方法就是book和sheet的操作。

        1)获取book中一个工作表

        table = data.sheets()[0]          #通过索引顺序获取
        table = data.sheet_by_index(sheet_indx)) #通过索引顺序获取

        table = data.sheet_by_name(sheet_name)#通过名称获取

        以上三个函数都会返回一个xlrd.sheet.Sheet()对象

        names = data.sheet_names()    #返回book中所有工作表的名字

        data.sheet_loaded(sheet_name or indx)   # 检查某个sheet是否导入完毕

        2)行的操作

         nrows = table.nrows  #获取该sheet中的有效行数

         table.row(rowx)  #返回由该行中所有的单元格对象组成的列表

         table.row_slice(rowx)  #返回由该列中所有的单元格对象组成的列表

         table.row_types(rowx, start_colx=0, end_colx=None)    #返回由该行中所有单元格的数据类型组成的列表

         table.row_values(rowx, start_colx=0, end_colx=None)   #返回由该行中所有单元格的数据组成的列表

         table.row_len(rowx) #返回该列的有效单元格长度

        3)列(colnum)的操作

         ncols = table.ncols   #获取列表的有效列数

         table.col(colx, start_rowx=0, end_rowx=None)  #返回由该列中所有的单元格对象组成的列表

         table.col_slice(colx, start_rowx=0, end_rowx=None)  #返回由该列中所有的单元格对象组成的列表

         table.col_types(colx, start_rowx=0, end_rowx=None)    #返回由该列中所有单元格的数据类型组成的列表

         table.col_values(colx, start_rowx=0, end_rowx=None)   #返回由该列中所有单元格的数据组成的列表

         4)单元格的操作

         table.cell(rowx,colx)   #返回单元格对象

         table.cell_type(rowx,colx)    #返回单元格中的数据类型

         table.cell_value(rowx,colx)   #返回单元格中的数据

         table.cell_xf_index(rowx, colx)   # 暂时还没有搞懂

 

demo:(读取)

import xlrd
import xlsxwriter
data=xlrd.open_workbook('test.xlsx')
table=data.sheets()[0]    #按照表格顺序,拿第一个
nrows=table.nrows
ncols=table.ncols
title_li=table.row_values(0)
# print(title_li)
JG=[]
for i in range(1,nrows):
    dic={}
    for c in range(ncols):
        dic[title_li[c]]=table.row_values(i)[c]
    JG.append(dic)
print(JG)
View Code

demo:(写入)

import xlwt as ExcelWrite
def writeXLS(file_name):
    JG = [{'服务器公网': '1.1.1.1', '服务器内网ip': '10.45.138.26', '服务器名称': 'web1', '服务器到期时间': 43218.0},
          {'服务器公网': '2.2.2.2', '服务器内网ip': '10.44.63.168', '服务器名称': 'web2', '服务器到期时间': 43222.0},
          {'服务器公网': '3.3.3.3', '服务器内网ip': '10.28.55.9', '服务器名称': '爬虫7', '服务器到期时间': 43211.0}]
    xls = ExcelWrite.Workbook()
    sheet = xls.add_sheet("Sheet1")
    title=list(JG[0].keys())
    for a in range(len(title)):
        sheet.write(0,a,title[a])
    for i in range(len(JG)):
        for j in range(0, len(JG[0])):
            hang_data=list(JG[i].values())
            sheet.write(i+1,j, hang_data[j])
    xls.save(file_name)
if __name__ == "__main__":
    writeXLS("test_write.xls");
View Code
原文地址:https://www.cnblogs.com/onda/p/8309771.html