做公司內部系統時,經常會遇到做表格數據的導出,表格導出很好實現,但是要實現帶圖片的導出就有點困難,下面樓主我分享一下自己寫的腳本。
導出數據裏面需要包含圖片連接,導出時會自動下載,並且保存到圖片。
需要導出的數據是 export_items,大家應該換成自己對應的數據源
head_filed 是 輸出表格的表頭字段哦
import xlsxwriter,os
from datetime import datetime
from io import BytesIO
from urllib.request import urlopen
def exportUnfishImgTask(head_dict,boday_items,path):
if not os.path.exists(path):
os.makedirs(path)
filename = "batchExport-{0}.xls".format(datetime.strftime(datetime.now(), "%Y%m%d%H%M%S"))
workbook = xlsxwriter.Workbook(os.path.join(path,filename))
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, "IMG")
worksheet.set_column(0, 0, 40)
for num, filed in head_dict.items():
worksheet.write(0, num + 1, filed)
worksheet.set_column(0, num + 1, 40)
for i in range(len(boday_items)):
worksheet.set_row(i + 1, 200)
img_url = boday_items[i]['img_url']
if img_url != '':
try:
img_data = BytesIO(urlopen(img_url).read())
worksheet.insert_image(i + 1, 0, img_url,
{'image_data': img_data, 'x_scale': 0.25, 'y_scale': 0.25, 'object_position': 1})
except Exception as e:
worksheet.write(i + 1, 0, img_url)
else:
worksheet.write(i + 1, 0, '')
for num, filed in head_dict.items():
row_item = boday_items[i]
worksheet.write(i + 1, num + 1, row_item[filed])
workbook.close()
return filename
if __name__ == '__main__':
#1,設置導出的表格列名字,默認圖片在第一列
head_filed = ['IMG','A','B','C','D']
#2,需要導出的內容,img_url 字段名不能變
export_items = [
{'img_url':'https://www.baidu.1.jpg','A':'aaa1','B':'bbb1','C':'cccc1',"D":'ddd1'},
{'img_url':'https://www.baidu.2.jpg','A':'aaa2','B':'bbb2','C':'cccc2',"D":'ddd2'},
{'img_url':'https://www.baidu.3.jpg','A':'aaa3','B':'bbb3','C':'cccc3',"D":'ddd3'},
]
#3,導出的文件存放地址
export_path_dir = '/home/user/Descktop/export'
#4,開始導出
exportUnfishImgTask(head_filed,export_items,export_path_dir)