Can't write data into Excel-Sheet using openpyxl Workbook
Question:
I’m trying to write to specific cells in a Excel-Sheet using openpyxl Workbook. 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.
What gives?
Answers:
When you’re saving workbook, provide full path, otherwise you will save it in a Python folder. I’m pretty sure that’s where your Excel workbook with new data resides.
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!
I’m trying to write to specific cells in a Excel-Sheet using openpyxl Workbook. 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.
What gives?
When you’re saving workbook, provide full path, otherwise you will save it in a Python folder. I’m pretty sure that’s where your Excel workbook with new data resides.
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!