程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python3-excel document operation (2): use the openpyxl library to process excel tables: insert pictures in the excel table

編輯:Python

1. Introduction

You can insert pictures into the excel sheet, which can be achieved by using the openpyxl library.

2.Code:

# -*- coding: utf-8 -*-import osimport sysimport timeimport openpyxlfrom openpyxl import load_workbookfrom openpyxl.drawing.image import Imagedef openxls_insert_img(fname,img_path):'''Insert picture'''wb=load_workbook(fname,data_only=True);sheet=wb['mysheet1'] #Get sheetimg = Image(img_path) #Select image#sheet.add_image(img) #Add picturesheet.add_image(img,"D3") #Add picturelocal_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))new_filename = "file_" + local_time + ".xlsx";wb.save(new_filename) #Don't forget to saveif __name__ == '__main__':#1. case1# openxls_create();#2.case2fname = 'Personnel list.xlsx';#openxls_read(fname)#3.case3img_path = "Niannujiao_Chibi nostalgia_image1.jpg";openxls_insert_img(fname,img_path)

Description:

1. Introduce the Image class:

from openpyxl.drawing.image import Image

2. Create an Image object:

img = Image(img_path)

3. Add pictures:

#sheet.add_image(img) #Add a picture in the uppermost corner of excel

sheet.add_image(img,"D3") #Add an image to the specified cell

4. Save:

wb.save(new_filename) #Don't forget to save

Results:

% python3 openxls_creat_read.py

%ls

Personnel list.xlsx openxls_creat_read.py file_20220729115746.xlsx

It can be seen that a new file "file_20220729115746.xlsx" is generated with the following contents:

Note, If you use

sheet.add_image(img) #Add a picture in the uppermost corner of excel

will block the content in Excel, because the picture is inserted from the top left corner.



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved