简体   繁体   中英

In Python have a list of tuples and for each tuple would like to put x[0] and x[1] into column A and B of an Excel spreadsheet

I used xlrd to pull an Excel file with prescription numbers and drug names. I then made a list of tuples that include the prescription number and drug name. The list looks like this:

[(123, enalapril), 
 (456, atenolol), 
 (789, lovastatin)
]

I would like to create a new Excel file that lists each prescription number in column A with the corresponding drug in column B . I plan to use xlsxwriter . Is there a way to do this with tuples?

A workaround I tried involved creating two separate lists (one of prescription numbers and one of drugs). It worked in this small example, but I would like to make this work reliably on a large scale. I am concerned that by using two separate lists somehow the prescription numbers may be matched to the wrong drug in the new Excel file. Thank you.

xlsxwriter makes it pretty straight forward to create a basic spreadsheet:

Code:

import xlsxwriter

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('my_excel.xlsx')
worksheet = workbook.add_worksheet()

# Some data we want to write to the worksheet.
data = [(123, 'enalapril'), (456, 'atenolol'), (789, 'lovastatin')]

# Iterate over the data and write it out row by row.
for row, line in enumerate(data):
    for col, cell in enumerate(line):
        worksheet.write(row, col, cell)

workbook.close()

Results:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM