python_excel操作

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

xlwt缺点,无法复制Excel格式

xlutils 可以复制Excel格式

一、安装第三方库

pip install xlrd

pip  install xlwt

pip install xlutils

二、第三方库的使用

1、xlrd  读Excel

import xlrd

book=xlrd.open_workbook("demo2.xls")
sheet1=book.sheet_by_index(0) #通过索引取TAB,且返回的是对象
#sheet1=book.sheet_by_name('sheet1')#通过名字取TAB,且返回的是对象

print(sheet1.row_values(1)) #取某一行的数据
print(sheet1.col_values(0)) #取某一列的数据

print(sheet1.cell_value(0,0)) #取某一单元格内容
print(sheet1.cell(0,0).value) #取某一单元格内容
print(sheet1.col_values(1,0,6)) #取从第一列的第0行到第6行的数据,不包含第6行

print(sheet1.name) #取TAB名称
print(sheet1.nrows) #取共多少行
print(sheet1.ncols) #取共多少列
print(sheet1.number) #取TAB的index
print(sheet1.row_len(0)) #每行的长度

2、xlwt 写Excel

import xlwt
book=xlwt.Workbook() #声明对象
sheet=book.add_sheet('标签1') #添加TAB签
list=["姓名","年龄","性别","班级"] #表头数据
x,y=0,0
for i in list:
 sheet.write(x,y,i)  #遍历写表头
 y+=1
book.save("b.xls") 
#保存的时候,如果你用的是微软的Office,后缀就用.xls
#如果是wps .xls,.xlsx

3、xlutils 复制修改

修改的思路是:打开----复制----修改

import xlrd
from xlutils import copy

book=xlrd.open_workbook("book.xls") #打开文件
newbook=copy.copy(book) #复制文件

sheet=newbook.get_sheet(0) #获取表TAB
list=["姓名","年龄","性别","班级"] 

for col,t in enumerate(list): #枚举方式遍历写表头
    sheet.write(0,col,t)
newbook.save("book.xls")

4、写复杂的EXCEL,涉及合并单元格

write_merge 这个方法可以合并单元格,write_merge(row,row+n,col,col+n,value)参数含义
import xlwt

def set_style(name,height,bold=False):
    style=xlwt.XFStyle()

    font=xlwt.Font()
    font.name=name
    font.bold=bold
    font.colour_index=4
    font.height=height


    style.font=font

    return style

def write_excel():
    f=xlwt.Workbook()

    sheet1=f.add_sheet(u'sheet1',cell_overwrite_ok=True)
    row0=[u'业务',u'状态',u'北京',u'上海',u'广州',u'深圳',u'状态小计',u'合计']
    column0 = [u'机票', u'船票', u'火车票', u'汽车票', u'其它']
    status = [u'预订', u'出票', u'退票', u'业务小计']

    for i in range(0,len(row0)):
        sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))
    i,j=1,0
    while i<4*len(column0) and j<len(column0):
        sheet1.write_merge(i,i+3,0,0,column0[j],set_style('Arial',220,True))
        sheet1.write_merge(i,i+3,7,7)
        i+=4
        j+=1
    sheet1.write_merge(21,21,0,1,u'合计',set_style('Times New Roman',220,True))

    i=0
    while i<4*len(column0):
        for j in range(0,len(status)):
            sheet1.write(j+i+1,1,status[j])
        i+=4
    f.save('demo1.xlsx')

if __name__=='__main__':
    write_excel()

 

原文地址:https://www.cnblogs.com/xiaokuangnvhai/p/11098677.html