excel表格支持带图片的导出

1.概述

#1,设置导出的表格列名字,默认图片在第一列
#2,需要导出的内容,img_url 字段名不能变
#3,导出的文件存放地址
#4,开始导出
 1 import xlsxwriter,os
 2 from datetime import datetime
 3 from io import BytesIO
 4 from urllib.request import urlopen
 5 
 6 
 7 
 8 def exportUnfishImgTask(head_dict,boday_items,path):
 9     if not os.path.exists(path):
10         os.makedirs(path)
11 
12     filename = "batchExport-{0}.xls".format(datetime.strftime(datetime.now(), "%Y%m%d%H%M%S"))
13     workbook = xlsxwriter.Workbook(os.path.join(path,filename))
14     worksheet = workbook.add_worksheet()
15 
16     worksheet.write(0, 0, "IMG")
17     worksheet.set_column(0, 0, 40)
18     for num, filed in head_dict.items():
19         worksheet.write(0, num + 1, filed)
20         worksheet.set_column(0, num + 1, 40)
21 
22     for i in range(len(boday_items)):
23         worksheet.set_row(i + 1, 200)
24         img_url = boday_items[i]['img_url']
25         if img_url != '':
26             try:
27                 img_data = BytesIO(urlopen(img_url).read())
28                 worksheet.insert_image(i + 1, 0, img_url,
29                                        {'image_data': img_data, 'x_scale': 0.25, 'y_scale': 0.25, 'object_position': 1})
30             except Exception as e:
31                 worksheet.write(i + 1, 0, img_url)
32         else:
33             worksheet.write(i + 1, 0, '')
34         for num, filed in head_dict.items():
35             row_item = boday_items[i]
36             worksheet.write(i + 1, num + 1, row_item[filed])
37     workbook.close()
38     return filename
39 
40 
41 
42 if __name__ == '__main__':
43     #1,设置导出的表格列名字,默认图片在第一列
44     head_filed = ['IMG','A','B','C','D']
45     #2,需要导出的内容,img_url 字段名不能变
46     export_items = [
47                     {'img_url':'https://www.baidu.1.jpg','A':'aaa1','B':'bbb1','C':'cccc1',"D":'ddd1'},
48                     {'img_url':'https://www.baidu.2.jpg','A':'aaa2','B':'bbb2','C':'cccc2',"D":'ddd2'},
49                     {'img_url':'https://www.baidu.3.jpg','A':'aaa3','B':'bbb3','C':'cccc3',"D":'ddd3'},
50                     ]
51     #3,导出的文件存放地址
52     export_path_dir = '/home/user/Descktop/export'
53 
54     #4,开始导出
55     exportUnfishImgTask(head_filed,export_items,export_path_dir)

 

posted @ 2020-05-15 20:05  Blues.huang  阅读(1318)  评论(0编辑  收藏  举报