python中 xlrd/xlwt模块详解 

python中 xlrd/xlwt模块详解 

 

1、什么是xlrd模块

python操作excel主要用到xlrd和xlwt两个库,即xlrd是读excel,xlwt是写excel库

一、安装xlrd模块

cmd窗口下 pip install xlrd

二、使用介绍

# -*- coding=utf-8 -*-

import xlrd  #导入读excel的模块

#打开excel
filename='C:/Users/YKDZ065/PycharmProjects/0830/jianlc/cases/Test.xlsx'
data=xlrd.open_workbook(filename,"rb")

#获取excel工作表
mysheets=data.sheets() #获取工作表list

#通过索引获取第一个sheet
mysheet=mysheets[0]

#通过索引顺序获取
#mysheet=data.sheet_by_index(0)

#通过名称获取
#mysheet=data.sheet_by_name(u'Sheet1')


#获取行数和列数
nrows=mysheet.nrows
print nrows
ncols=mysheet.ncols
print ncols

#获取一行和一列
#myRowValues=mysheet.row_values(0)
#print myRowValues
#myColValues=mysheet.col_values(0)
#print myColValues

#读取单元格数据
for i in range(ncols):
    for j in range(nrows):
        myCell=mysheet.cell(j,i)
        myCellValue=myCell.value
        print myCellValue

2、使用xlwt模块写入excel文件

# -*- coding=utf-8 -*-
#导入模块
import  xlwt

#创建excel工作薄
myWorkbook=xlwt.Workbook()

#添加Excel工作表
mySheet=myWorkbook.add_sheet("a Test Sheet")

#写入数据
myStyle=xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00') #数据格式
mySheet.write(1,1,1234.56,myStyle)
mySheet.write(2,0,1)
mySheet.write(2,1,1)
mySheet.write(2,2,xlwt.Formula("A3+B3"))


myWorkbook.save("excelFile.xlsx")

 

3、xlutils结合xlrd可以达到修改excel文件目的

# -*-  coding=utf-8  -*-
#修改excel文件
#导入包
import  xlrd
from xlutils.copy import copy
filename='C:/Users/YKDZ065/PycharmProjects/0830/jianlc/cases/Test.xlsx'
workbook=xlrd.open_workbook(filename)
workbooknew=copy(workbook)
ws=workbooknew.get_sheet(0)
ws.write(0,1,"changed")
workbooknew.save("Testcopy.xlsx")

 

# -*- coding=utf-8 -*-
# author=zyq
import  xlrd #读excel的模块
import xlwt  #写excel的模块
#操作excel文件

def opExcel():
    filename='excelFile.xlsx'  #定义一个excel文件
    excelFile=xlrd.open_workbook(filename)  #打开excel文件

    table=excelFile.sheets()[0] #通过索引获取第一个sheet表
    #table=excelFile.sheet_by_index(0) #通过索引获取第一个sheet表
    #table=excelFile.sheet_by_name(u"a Test Sheet")# 通过名字获取sheet表

    #获取整行的值
    print table.row_values(0) #获取第一行的值,以列表的形式返回
    print table.col_values(0)  #获取第一列的值,以列表的形式返回

    #获取行数和列表
    print table.nrows #获取行数
    print table.ncols  #获取列表

    #根据行数遍历所有行数的值
    for i in range(table.nrows):
        print table.row_values(i)

    #获取单元格的值
    cell_A1=table.cell(0,0).value  #获取A1位置的数据,行和列的所有位置都是从0开始的
    print cell_A1

    #使用行列所有确定单元格的数据
    cell_A1=table.row(0)[0].value
    print cell_A1
    #获取所有单元格的值
    for i in range(table.nrows):
        for j in range(table.ncols):
            print table.cell(i,j).value

opExcel()
# 对excel的写操作
def writeExcel():
    #创建excel
    mybook=xlwt.Workbook()
    #添加excel工作表
    mySheet=mybook.add_sheet("a")
    #写入数据
    mySheet.write(4,4,'test')

    mybook.save("1.xlsx")
writeExcel()

# -*- coding: utf-8 -*-
import  xdrlib ,sys
import xlrd
def open_excel(file= 'file.xls'):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception,e:
        print str(e)
#根据索引获取Excel表格中的数据   参数:file:Excel文件路径     colnameindex:表头列名所在行的所以  ,by_index:表的索引
def excel_table_byindex(file= 'file.xls',colnameindex=0,by_index=0):
    data = open_excel(file)
    table = data.sheets()[by_index]
    nrows = table.nrows #行数
    ncols = table.ncols #列数
    colnames =  table.row_values(colnameindex) #某一行数据
    list =[]
    for rownum in range(1,nrows):

         row = table.row_values(rownum)
         if row:
             app = {}
             for i in range(len(colnames)):
                app[colnames[i]] = row[i]
             list.append(app)
    return list

#根据名称获取Excel表格中的数据   参数:file:Excel文件路径     colnameindex:表头列名所在行的所以  ,by_name:Sheet1名称
def excel_table_byname(file= 'file.xls',colnameindex=0,by_name=u'Sheet1'):
    data = open_excel(file)
    table = data.sheet_by_name(by_name)
    nrows = table.nrows #行数
    colnames =  table.row_values(colnameindex) #某一行数据
    list =[]
    for rownum in range(1,nrows):
         row = table.row_values(rownum)
         if row:
             app = {}
             for i in range(len(colnames)):
                app[colnames[i]] = row[i]
             list.append(app)
    return list

def main():
   tables = excel_table_byindex()
   for row in tables:
       print row

   tables = excel_table_byname()
   for row in tables:
       print row

if __name__=="__main__":
    main()

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值