簡體   English   中英

使用openpyxl將字典的python列表寫入xlsx

[英]write python list of dicts to xlsx using openpyxl

我嘗試使用dicts openpyxlsx字典list寫入xlsx文件

products= [{'id':46329', 
            'discription':'AD BLeu', 
            'marque':'AZERT',
            'category':'liquid',
            'family': 'ADBLEU', 
            'photos':'D:\\hamzawi\\hamza\\image2py\\46329_1.png'},
            {dict2 ...},
            {dictn...}
           ]

 # creat a workbook
 filena = "produitimage.xlsx"
 workbook = Workbook()
 sheet = workbook.active
 #add headers
 sheet.append(["Product ID", "Product Name", "Marque",
          "Category", "Family", "Photos"])
 for product in products:
    for item in product.items():
        for row, entry in enumerate(item, start=3):
            sheet.cell(row=row, column=1, value=entry)
 #add some images
 images = [item['photos'] for item in products]
 for image in images:
     logo = Image(image)
     #logo.height = 150
     #logo.width = 150
     sheet.add_image(logo)
 workbook.save(filename=filena)

我得到了只有標題沒有數據的 xlsx 文件

問題:append dict list

import openpyxl

products = [{'id':46329, 
             'discription':'AD BLeu', 
             'marque':'AZERT',
             'category':'liquid',
             'family': 'ADBLEU', 
             'photos':'D:\\hamzawi\\hamza\\image2py\\46329_1.png'}
            ]

# Dictionarys are not in order by default
# Define a `list` of `keys` in desired order
fieldnames = ['id', 'discription', 'marque', 'category', 'family', 'photos']

# create a new workbook
wb = openpyxl.Workbook()
ws = wb.active

# append headers
ws.append(["Product ID", "Product Name", "Marque", "Category", "Family", "Photos"])

# append data
# iterate `list` of `dict`
for product in products:
    # create a `generator` yield product `value`
    # use the fieldnames in desired order as `key`
    values = (product[k] for k in fieldnames)

    # append the `generator values`
    ws.append(values)

# show Worksheet Values
for row_values in ws.iter_rows(values_only=True):
    for value in row_values:
        print(value, end='\t')
    print()

Output

 Product ID Product Name Marque Category Family Photos 46329 AD BLeu AZERT liquid ADBLEU D:\hamzawi\hamza\image2py\46329_1.png

如果您想要圖像,而不是圖像文件路徑,請更改以下內容:

# remove 'photos' from fieldnames
fieldnames = \
['id', 'discription', 'marque', 'category', 'family']

# you need the Row index, add a `enumerate(..., 2)`
for row, product in enumerate(products,2):
    values = (product[k] for k in fieldnames)
    sheet.append(values)

    # after append the `values` add the image
    # Here, Column 'F'
    ws.add_image(Image(product['photos']), 'F{}'.format(row))

您的代碼中存在一些問題。
首先,您在設置它的循環中遞增next_row值,因此遞增無效,並且每次迭代next_row的值都等於 3。
其次,您正在嘗試將 dict 值列表寫入 excel 單元格,但我認為您希望將其寫入一行。 所以你只需要 append 就像你在循環上方使用 header 一樣:

for product in products:
    sheet.append(list(product.values()))

如果您需要在一行的最后一個單元格中插入圖像,您可以這樣重寫循環:

for row_index, product in enumerate(products):
    values = list(product.values())
    sheet.append(values[:-1])
    col_row = get_column_letter(len(values)) + str(row_index+1) 
    photo_path = values[-1]
    sheet.add_image(Image(photo_path), col_row)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM