我正在尝试创建订单数据库。每次程序运行并且用户输入数据时,都会创建一个包含此数据的不同列表。在程序结束时,我将此数据添加到数据库中。 我目前使用它来连接多个列表并以我需要的格式输入到数据库。
orderNumber = ['123456789']
countryOfOrigin = ['United Kingdom']
sizeList = ['2', '4']
quantityList = ['10', '12']
这是我得到的输出:
OrderNumber COO Size QTY
123456789 United Kingdom 2 10
123456789 United Kingdom 4 20
注意:行数由尺寸数决定...如果其他列表只有一项,则数据会向下复制以填充行。
这是用于创建 DataFrame 的代码。
vals = [orderNumber, countryOfOrigin, sizeList, quantityList]
header = ["OrderNumber", "COO", "Size", "QTY"]
d = {a: b[0] if len(b) == 1 else b for a, b in zip(header, vals)}
order = pd.DataFrame(d)
并且只需使用以下命令将其保存到文档中:
order.to_excel('C:/Users/userName/Desktop/Pandas-Example2.xlsx', index=False, encoding='utf-8')
这一切都有效,但如果文档在提供的位置路径中不可用,则会创建一个。如果它已经在那里了。每次程序运行时,数据都会被新数据替换。
我需要它不是替换已有的内容,而是找到最后填充的行,跳过一行(以创建一个行间隙)并填充下面的新数据。
我尝试指定以下行:
bottom = excelFile.tail(1)
order.to_excel('C:/Users/userName/Desktop/Pandas-Example2.xlsx',
index=False, encoding='utf-8', startrow=bottom, startcol=1)
没有运气。
最佳答案
我认为这可能对您有帮助:https://stackoverflow.com/a/47740262/10740287
通过使用辅助函数 append_df_to_excel
以及参数 index=False
和 encoding='utf-8'
你应该得到你想要的。
append_df_to_excel('C:/Users/userName/Desktop/Pandas-Example2.xlsx', order, index=False, encoding='utf-8)
关于python - Pandas,附加到 Excel 中的下一个可用行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773146/