I'm a first time user of openpyxl and am struggling with basic Cell editing. In the following code I'm trying to change the Cell Value "B3" in my Excel File to a String Value (eg. "Germany").
What I don't seem to understand is why the openpyxl Worksheet & Worbook are an immutable tuple type and the Documentation is suggesting the simple Cell Assignment I'm using.
Here's my Code:
from openpyxl import Workbook
from openpyxl import load_workbook
# 1. Open Excel File
wb = Workbook()
wb = load_workbook(filename="myFile.xlsm", read_only=True, keep_vba=True, data_only=True)
ws = wb.active[1] # ws is the second Worksheet in the Workbook
# 2. Enter Input (Country)
ws["B3"] = "Germany"
wb.save("myFile.xlsm")
ws["B3"] = "Germany" TypeError: 'tuple' object does not support item assignment
Expectation I expected to find a Excel file that contains my assigned value in the given cell.
I appreciate every answer - thanks!
CodePudding user response:
Line ws = wb.active[1]
is probably wrong. Also you should use read_only=False
(simply remove this param, the default is False
) if you want to modify the file.
You can assign ws by name. If you don't know the names you can list them like this:
>>> wb.sheetnames
['Sheet1', 'Sheet2', 'Sheet3']
>>> ws = wb['Sheet2'] # or ws = wb.active - "Get the currently active sheet"
>>> ws["B3"] = "Germany"
Whole code:
from openpyxl import Workbook
from openpyxl import load_workbook
# 1. Open Excel File
wb = Workbook()
wb = load_workbook(filename="myFile.xlsm", keep_vba=True, data_only=True)
ws = wb.active # the currently active sheet
# 2. Enter Input (Country)
ws["B3"] = "Germany"
wb.save("myFile.xlsm")