使用模块xlsxwriter
插入的图片大小需要自己压缩(我用了PIL)
注意设置列宽和行高的时候,像素与excel样式的单位转换, 列宽约等于8像素 行高约等于1.37像素。
#部分代码
import xlsxwriter
from PIL import Image
def img_resize(infile,outfile):
im = Image.open(infile)
# (x, y) = im.size # read image size
x_s = 120 # define standard width
y_s = 160 # calc height based on standard width
out = im.resize((x_s, y_s), Image.ANTIALIAS) # resize image with high-quality
out.save(outfile)
def gen_xls(item_infos):
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
book = xlsxwriter.Workbook('amazon%s.xlsx'%timestamp)
worksheet = book.add_worksheet('demo')
worksheet.write_row(0,0, ['关键词','排名','宝贝图片','价格','宝贝类目','宝贝描述','宝贝链接'])
worksheet.set_column('A:D', 15) # 列宽约等于8像素 行高约等于1.37像素
worksheet.set_column('C:C', 20)
worksheet.set_column('B:B', 10)
worksheet.set_column('F:F', 50)
for i in range(len(item_infos)):
col = i+1
try:
item_info = item_infos[i]
row = [item_info['keyword'],item_info['rank'],'',item_info['price'],item_info['cat'],item_info['descriptions'],item_info['item_url']]
worksheet.write_row(col,0, row)
worksheet.set_row(col, 120)
if 'item_pic_base64' in item_info:
item_pic_base64 = item_info["item_pic_base64"]
try:
if 'https:' in item_pic_base64:
data = requests.get(item_pic_base64)
else:
data = base64.b64decode(item_pic_base64)
with open('test.png', 'wb') as f:
f.write(data)
img_resize('test.png', 'img/tmp%s.png'%i)
worksheet.insert_image( col,2, 'img/tmp%s.png'%i) # 名字必须不同
except Exception,e:
print str(e)
except Exception,e:
print e,item_info
print '完成结果数,%s'%col
book.close()
实际效果