1、 安装
pip install openpyxl 这样就可以了
想要在文件中插入图片文件,需要安装pillow,安装文件:PIL-fork-1.1.7.win-amd64-py2.7.exe
· font(字体类):字号、字体颜色、下划线等
· fill(填充类):颜色等
· border(边框类):设置单元格边框
· alignment(位置类):对齐方式
· number_format(格式类):数据格式
· protection(保护类):写保护
2、 创建一个excel 文件,并写入不同类的内容
from openpyxl import Workbook
wb = Workbook() #创建文件对象
# grab the active worksheet
ws = wb.active #获取第一个sheet
# Data can be assigned directly to cells
ws['A1'] = 42 #写入数字
ws['B1'] = "你好"+"automation test" #写入中文(unicode中文也可)
# Rows can also be appended
ws.append([1, 2, 3]) #写入多个单元格
# Python types will automatically be converted
import datetime
import time
ws['A2'] = datetime.datetime.now() #写入一个当前时间
#写入一个自定义的时间格式
ws['A3'] =time.strftime("%Y年%m月%d日 %H时%M分%S秒",time.localtime())
# Save the file
wb.save("test.xlsx")
3、 创建sheet
from openpyxl import Workbook
wb = Workbook()
ws1 = wb.create_sheet("Mysheet") #创建一个sheet
ws1.title = "New Title" #设定一个sheet的名字
ws2 = wb.create_sheet("Mysheet", 0) #设定sheet的插入位置 默认插在后面
ws2.title = u"你好" #设定一个sheet的名字 必须是Unicode
ws1.sheet_properties.tabColor = "1072BA" #设定sheet的标签的背景颜色
#获取某个sheet对象
print wb.get_sheet_by_name(u"你好" )
print wb["New Title" ]
#获取全部sheet 的名字,遍历sheet名字
print wb.sheetnames
for sheet_name in wb.sheetnames:
print sheet_name
print "*"*50
for sheet in wb:
print sheet.title
#复制一个sheet
wb["New Title" ]["A1"]="zeke"
source = wb["New Title" ]
target = wb.copy_worksheet(source)
w3 = wb.copy_worksheet(wb['new title'])
ws3.title = 'new2'
wb.copy_worksheet(wb['new title']).title = 'hello'
4、 操作单元格
from openpyxl import Workbook
wb = Workbook()
ws1 = wb.create_sheet("Mysheet") #创建一个sheet
ws1["A1"]=123.11
ws1["B2"]="你好"
d = ws1.cell(row=4, column=2, value=10)
print ws1["A1"].value
print ws1["B2"].value
print d.value
5、 操作批量的单元格
无论ws.rows还是ws.iter_rows都是一个对象
除上述两个对象外 单行,单列都是一个元组,多行多列是二维元组
from openpyxl import Workbook
wb = Workbook()
ws1 = wb.create_sheet("Mysheet") #创建一个sheet
ws1["A1"]=1
ws1["A2"]=2
ws1["A3"]=3
ws1["B1"]=4
ws1["B2"]=5
ws1["B3"]=6
ws1["C1"]=7
ws1["C2"]=8
ws1["C3"]=9
#操作单列
print ws1["A"]
for cell in ws1["A"]:
print cell.value
#操作多列,获取每一个值
print ws1["A:C"]
for column in ws1["A:C"]:
for cell in column:
print cell.value
#操作多行
row_range = ws1[1:3]
print row_range
for row in row_range:
for cell in row:
print cell.value
print "*"*50
for row in ws1.iter_rows(min_row=1, min_col=1,