[英]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.
交易数据应该包含一个国家 - 如果没有,它应该给出 N/A。 How can I loop the transactions data into column 1 and the country name into column 2?
如何将交易数据循环到第 1 列,将国家名称循环到第 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.我建议使用 pandas 而不是直接写入文件。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.