简体   繁体   English

无法使用 openpyxl Workbook 将数据写入 Excel-Sheet

[英]Can't write data into Excel-Sheet using openpyxl Workbook

I'm trying to write to specific cells in a Excel-Sheet using openpyxl Workbook.我正在尝试使用 openpyxl 工作簿写入 Excel 工作表中的特定单元格。 At first I couldn't write to cells that already had data in them and now I can't write at all (or I'm just going crazy).起初我无法写入已经有数据的单元格,现在我根本无法写入(或者我快疯了)。

Here's my code:这是我的代码:

    wb = load_workbook("..\\..\\Decision Tree Classifier  TPS\\Decision Tree Classifier  TPS\\TestData.xlsx")
    ws1 = wb.get_sheet_by_name("Sheet1")

    #this works
    print(ws1.cell(row=1, column=1).value)

    #these do not
    ws1['D3'] = 5
    ws1.cell(row=5, column=1).value = "SomeValue2"
    ws1.cell(row=7, column=1,value='Hey')
    ws1.cell(row=6, column=1).value = 'TEST'

    wb.save("TestData.xlsx")

I get no errors, the print line works, the write lines do not.我没有收到任何错误,打印行有效,写入行无效。

Similar problem here Writing data into Excel-Sheet using openpyxl isn't working , except I have the save function.类似的问题在这里使用 openpyxl 将数据写入 Excel-Sheet 不起作用,除非我有保存功能。

What gives?是什么赋予了?

When you're saving workbook, provide full path, otherwise you will save it in a Python folder.保存工作簿时,请提供完整路径,否则会将其保存在 Python 文件夹中。 I'm pretty sure that's where your Excel workbook with new data resides.我很确定这就是包含新数据的 Excel 工作簿所在的位置。

wb.save("..\\..\\Decision Tree Classifier  TPS\\Decision Tree Classifier  TPS\\TestData.xlsx")

Also, don't forget to close your workbook when you're done with it.另外,不要忘记在完成工作簿后关闭它。

wb.close()

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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