简体   繁体   中英

python write to excel overwrite cell

I have one list with country names and one list with strings containing transaction data. The transaction data should contain a country - if not, it should give N/A. How can I loop the transactions data into column 1 and the country name into column 2? This is my attempt so far, but it returns that I overwrite cells.

FYI: the length of transaction data < the length of country names.

for i in range(len(transactions)):
    ws.write(i, 0, transactions[i])                   #Paste transaction data into column 0
    for country in countries:
        if country in transactions[i]:
            ws.write(i,1,country)
        else:
            ws.write(i,1,"N/A")

Any suggestions to solve this problem?

I would suggest to use pandas instead of writing to the file directly. If I understood your problem correctly, then something like this should work:


excel_table = {
    "transactions": [],
    "countries": [],
}

for i, transaction in enumerate(transactions): 
    for country in countries:
        if country in transaction: 
            excel_table["transactions"].append(transaction)
            excel_table["countries"].append(country)
            break
    else: 
        excel_table["transactions"].append(transaction)
        excel_table["countries"].append("N/A")

df = pd.DataFrame(excel_table)

df.to_excel("path.xlsx")

Also, remember to install the necessary dependencies:

pip install pandas
pip install openpyxl

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