python 使用openpyxl创建excel并写入数据
import openpyxl,PIL
from PIL import Image
import os
file_path = 'D:/1.xlsx'
if not os.path.exists(file_path):
wb = openpyxl.Workbook()
print("新建Excel:" + file_path + "成功")
ws=wb.active
fields=["id", "text", "res1", "res2", "res3", "res4", "res4", "label"]
for field in range(1,len(fields)+1):
_=ws.cell(row=1,column=field,value=str(fields[field-1]))
wb.save(filename=file_path)
else:
wb = openpyxl.load_workbook(file_path)
wbname='Sheet'
ws=wb.get_sheet_by_name(wbname)
for i in range(2,11,1):
_ = ws.cell(row=i, column=1, value=str(i-1))
_ = ws.cell(row=i, column=2, value="aaaaa")
for j in range(1, 6):
img_file_path = os.path.join('D:/1.jpg')
img = Image.open(img_file_path)
img = img.resize((110, 110),Image.ANTIALIAS)
img_column = chr(65 + j + 1)
ws.column_dimensions[img_column].width = 20
ws.row_dimensions[i].height = 85
ws.add_image(img, anchor=img_column + str(i))
wb.save(filename=file_path)