Search code examples
pythonlistfor-loopdebuggingexport-to-excel

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?


Solution

  • 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