openpyxl的使用(二)

利用pip安装openpyxl模块包
py -3 -m pip install openpyxl

excel文件写入数据
#coding=utf-8
from openpyxl import Workbook
wb = Workbook() #创建文件对象

ws = wb.active #获取第一个 sheet

ws['A1'] = 42 #写入数字

ws.append([1, "china", "中国"])
import datetime
print type(datetime.datetime.now())
ws["A3"] = datetime.datetime.now()

wb.save(u"第一个文件.xlsx")

创建操作sheet
#coding=utf-8
from openpyxl import Workbook
wb = Workbook()
ws1 = wb.create_sheet(u"光荣之路") #创建一个 sheet

ws2 = wb.create_sheet("Mysheet", 0)
ws2.title = u"python excel 操作练习"

ws1.sheet_properties.tabColor = "1072BA" #设定 sheet 的标签的背景颜色
ws2.sheet_properties.tabColor = "FFFF00"

#通过名字获取某个 sheet 对象
ws3 = wb[u"python excel 操作练习"]

print ws3.title

#通过名字获取某个 sheet 对象
ws4 = wb.get_sheet_by_name(u"光荣之路")

print ws4.title

#打印所有的excel中的sheet名字,返回列表
print wb.sheetnames

#遍历输出excel中的所有sheet名字
for sheet in wb:
print(sheet.title)

print "****"
#打印sheet的名字,返回列表
print wb.get_sheet_names()

ws5 = wb.get_sheet_by_name(wb.get_sheet_names()[0])
print ws5.title

Save the file

wb.save(u"创建sheet2.xlsx")

创建4个sheet
from openpyxl import Workbook

wb = Workbook()
wbs1 = wb.create_sheet(u"光荣之路1")
wbs2 = wb.create_sheet(u"光荣之路2")
wbs3 = wb.create_sheet(u"光荣之路3")
wbs4 = wb.create_sheet(u"光荣之路4")

wbs1["A1"] = u"中"
wbs2["A1"] = u"国"
wbs3["A1"] = u"你"
wbs4["A1"] = u"好"

wb.save("gloryroad.xlsx")

猜你喜欢

转载自blog.51cto.com/13496943/2136530
今日推荐