【python】使用openpyxl创建excel并写入数据

python 使用openpyxl创建excel并写入数据

# '''
# 实现功能:
#     在excel中,对应的名称后面,插入图片, 文字等
#
# '''
#
import openpyxl,PIL
from PIL import Image
import os

# # 新建excel
file_path = 'D:/1.xlsx'  # 设置路径
if not os.path.exists(file_path):
    wb = openpyxl.Workbook()
    # wb.save(filename=file_path)
    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)
    # #获取sheet页
    wbname='Sheet'
    ws=wb.get_sheet_by_name(wbname)  #获取工作表

for i in range(2,11,1):  # 行,从第二行开始,第一行为表头
    # i行设置第一二列,插入数据
    _ = 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(img_file_path)
        # #设置图片的大小
        # img.width, img.height = (110, 110)
        # 获取图片
        img = Image.open(img_file_path)
        # 设置图片的大小
        img = img.resize((110, 110),Image.ANTIALIAS)
        # 设置表格的宽20和高85
        img_column = chr(65 + j + 1)  # 由A(65)列开始,
        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)  # 保存
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值