实现excel文件创建和追加内容
import time
import openpyxl
stime = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
def openpyxl_create(fileName):
path = '../report/' + fileName + ".xlsx"
tableName1 = 'Report'
tableName2 = 'OperateTime'
data = openpyxl.Workbook()
data.create_sheet(tableName1)
table = data.get_sheet_by_name(tableName1)
ncols = 1
values = ["设备IP", "功放开关", "核心板软重启", "核心板断电重启", "测试结果"]
for value in values:
table.cell(1, ncols, value)
ncols = ncols + 1
data.create_sheet(tableName2)
table = data.get_sheet_by_name(tableName2)
values = ["设备IP", "功放开启时间", "功放关闭时间", "核心板软重启时间", "核心板断电重启时间", "主控重启时间"]
ncols = 1
for value in values:
table.cell(1, ncols, value)
ncols = ncols + 1
data.save(path)
def openpyxl_addin(fileName,tableName,dataList):
fileName = '../report/' + fileName + ".xlsx"
data = openpyxl.load_workbook(fileName)
table = data.get_sheet_by_name(tableName)
print(table.title)
nrows = table.max_row
ncolumns = table.max_column
values = dataList
col = 1
for value in values:
print("value:%s,col:%d"%(value,col))
table.cell(nrows + 1, col).value = value
col += 1
data.save(fileName)
if __name__=='__main__':
filename = stime
tableName1 = 'Report'
tableName2 = 'OperateTime'
values = ['192.168.3.200', "Y", 'Y', 'Y', 'Y']
openpyxl_create(filename)
for i in range(10):
openpyxl_addin(filename,tableName1,values)
效果如下:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5adecc55b0871f9897796b6a49de6173.png)