python针对excel的操作技巧

yipeiwu_com5年前Python基础

一. openpyxl读

95%的时间使用的是这个模块,目前excel处理的模块,只有这个还在维护

1、workBook

workBook=openpyxl.load_workbook('path(.xlsx)').encode('gbk')
print workBook

2、sheet

sheetList=workBook.get_sheet_names() 获取所有sheet的名称,保存为列表格式
print sheetList

3、cell

(1)sheet1=workBook.get_sheet_by_name('test1') 获取某一个具体的sheet

(2)rowsData=sheet1.rows 获取所有的行,返回一个迭代器

行和列都是从1开始的,不是从0

for i in rowsData:
#print i
#print type(i) 元组格式
for j in i:
print j.coordinate(每一个cell的下表),j.value(cell的值), 打印出所有cell的内容
print

(3)colsData=sheet1.columns 获取所有的列,并返回迭代器

(4)更新某个单元格

j.value=u'重新赋值'
workBook.save(path(之前操作的路径))

 4、单元格的定位

两种方式:

(1)c1=sheet1.cell(coordinate='B2')

print c1.value

(2)c2=sheet1['B2'] 字典格式:通过key值找value

print c2.value

(3)c1=sheet1.cell(row=2,column=3) 第二行第三列

print c1.value

(4)切片,获取一个区域的单元格

area=sheet1['C2':'D7'] 得到一个元组
print area 元组里面嵌套元组
for i in area:
# print i
for j in i:
pass
# print j
print j.coordinate,
j.value = j.coordinate
print

二、写单元格

1、写workBook

workBook=openpyxl.Workbook()

2、sheet

sheet1=workBook.create_sheet(title='sheet1',index=0)
index=0 定位第几个sheet

3、cell

sheet1['B6'].value=u'testB6'
workBook.save(path)

4、在下一空行整行写入

sheet1.append([1,2,3,4,5,6,7])

三、excel相关的样式操作

import openpyxl
from openpyxl.styles import PatternFill,Alignment,Font,colors
workBook=openpyxl.Workbook()
sheet1=workBook.create_sheet('test')

1、合并单元格,两种方式

sheet1.merge_cells(range_string='A2:G2')
sheet1.merge_cells(start_row=2,start_column='A',end_row=2,end_column='G')

2、设置排版样式:对齐方式

al=Alignment(horizontal='center') horizontal:left,center,right
sheet1['A2'].alignment=al 

3、设置背景颜色

fill=PatternFill(patternType='solid',fgColor=colors.BLUE)
sheet1['A2'].fill=fill 

4、字体的颜色

sheet1[A2].value
font=Font(colors=colors.WHITE,size=14)
sheet1['A2'].font=font

总结

以上所述是小编给大家介绍的python针对excel的操作方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

详解django中使用定时任务的方法

今天介绍在django中使用定时任务的两种方式。 方式一: APScheduler 1)安装: pip install apscheduler 2)使用: from apsc...

python根据时间获取周数代码实例

时间 时间和周数 import time import datetime # 获取今天是第几周 print(time.strftime('%W')) # 获取当前是周几(0-6,0...

Python代码解决RenderView窗口not found问题

Python代码解决RenderView窗口not found问题

源起   Error:setParent: Object 'renderView' not found   这是一个在工作中很常见的问题,以前做特效的时候有10%的概率会碰到,多发生在打...

Python安装模块的常见问题及解决方法

1、error: command ‘x86_64-linux-gnu-gcc' failed with exit status 解决办法: # Python 3 $ sudo apt...

用python记录运行pid,并在需要时kill掉它们的实例

我在跑爬虫程序的时候,由于爬虫程序的等待目标服务器返回数据的时间很长,而cpu占用很低,所以经常挂着代理一跑就跑好几百个。但是爬虫程序通常是写了死循环,或直到分配给该进程的任务都跑完才退...