安装命令:
py -3 -m pip install openpyxl==2.5.4
# -*- coding: utf-8 -*-
import locale
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" #写入中文
# Rows can also be appended
ws.append([1, 2, 3]) #在新的一行写入多个单元格
wb.save(r"F:\Faker\python\gloryload\20181223\a.xlsx")
import datetime
import time
import locale
from openpyxl import Workbook
wb = Workbook() #创建文件对象
# grab the active worksheet
ws = wb.active #获取第一个sheet
ws['A2'] = datetime.datetime.now() #写入一个当前时间
#写入一个自定义的时间格式
locale.setlocale(locale.LC_CTYPE, 'chinese')
ws['A3'] =time.strftime("%Y年%m月%d日 %H时%M分%S秒",time.localtime())
# Save the file
wb.save(r"F:\Faker\python\gloryload\20181223\a.xlsx")
# 必须关闭.xlsx文件再执行,否则会报PermissionError
# -*- coding: utf-8 -*-
from openpyxl import Workbook
wb = Workbook()
ws = wb.create_sheet("Mysheet1")
ws1 = wb.create_sheet("Mysheet") #创建一个sheet
ws1.title = "New Title" #设定一个sheet的名字
ws2 = wb.create_sheet("Mysheet", 0) #设定sheet的插入位置
ws2.title = u"光荣之路自动化测试培训" #设定一个sheet的名字
ws1.sheet_properties.tabColor = "1072BA" #设定sheet的标签的背景颜色
#获取某个sheet对象
print (wb["光荣之路自动化测试培训"])
print (wb["New Title" ])
#获取全部sheet 的名字,遍历sheet名字
print (wb.sheetnames)
for sheet_name in wb.sheetnames:
print (sheet_name)
print ("*"*50)
#遍历获取sheet对象,按照sheet顺序获取
for sheet in wb:
print (sheet)
for sheet in wb:
print (sheet.title)
#复制一个sheet
wb["New Title" ]["A1"]="gloryroad"
source = wb["New Title" ]
target = wb.copy_worksheet(source)
del wb["New Title"] # 删除表
wb.save("b.xlsx")